2014-09-12 87 views
0

我有下面的代码,其将图形从边列表邻接矩阵:我怎样才能平行解析python?

for line in open('graph.txt'): 
    converted = [sparse_to_dense.get(int(ID)) for ID in line.split()] 
    i = converted[0] 
    j = converted[1] 
    I.append(i) 
    J.append(j) 
n = max([max(I), max(J)]) + 1 
data = [1]*len(I) 
return coo_matrix((data, (I,J)), shape=(n,n), dtype='i1') 

此代码是非常缓慢 - 上的500K边缘可以机转换发生小时。另一方面,I/O显然不是瓶颈(我几乎可以瞬间读完内存中的完整文件),所以我认为有一个并行的空间。但我不知道如何继续:我应该平行读文件吗?

+0

[为什么不考虑线程?](http://www.tutorialspoint.com/python/python_multithreading.htm) – heinst 2014-09-12 13:31:33

+1

@heinst我可能是错的,但解决了穿线问题是IO是瓶颈,大部分时间程序等待IO。在我的情况下,程序吃了100%的一个cpu,io在这里可以忽略不计。 – Moonwalker 2014-09-12 13:39:23

+0

我想你关心你对我和J.的正确顺序? – gosom 2014-09-12 13:42:20

回答

0

使用多重处理的一种方法就是这样做。我没有检查,并可以进一步改进

import multiprocessing 


class Worker(multiprocessing.Process): 

    def __init__(self, queue, results): 
     multiprocessing.Process.__init__(self): 
     self.q = queue 
     self.results = results 

    def run(self): 
     while True: 
      try: 
       lineno, linecontents = self.q.get(block=False) 
      except Queue.Empty: 
       break 
      converted = [sparse_to_dense.get(int(ID)) for ID in line.split()] 
      i = converted[0] 
      j = converted[1] 
      self.results.put((i, j)) 


def main(): 
    q = multiprocessing.Queue() 
    results = multiprocessing.JoinableQueue() 

    for i, l in open(fname): 
     q.put((i, l)) 

    for _ in xrange(4): 
     w = Worker(q, results) 
     w.start() 

    I, J = [] 
    while True: 
     try: 
      i, j = results.get(block=False) 
     except Queue.Empty: 
     break 
    I.append(i) 
    J.append(j) 
    results.task_done() 

    results.join() 

    n = max([max(I), max(J)]) + 1 
    data = [1]*len(I) 
    coo = coo_matrix((data, (I,J)), shape=(n,n), dtype='i1') 
+2

'results.get()'永远不会引发'Queue.Empty'异常。它会在'results'为空时阻止。你需要使用'get_nowait()'来代替。 'main'中的缩进似乎也是关闭的。 – dano 2014-09-12 15:43:58