如何在python中进行并行解析?
我有以下代码将图形从边列表转换为邻接矩阵:如何在python中进行并行解析?,python,graph,io,parallel-processing,multiprocessing,Python,Graph,Io,Parallel Processing,Multiprocessing,我有以下代码将图形从边列表转换为邻接矩阵: 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) retur
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')
这个代码非常慢——5月份机器上转换500k边需要几个小时。另一方面,i/o显然不是瓶颈(我几乎可以在瞬间读取内存中的完整文件),因此我认为存在并行空间。但我不知道如何继续:我应该并行读取文件还是什么 使用多处理一种方法就是这样。我没有检查,可以进一步改进
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')
@heinst I可能是错的,但当IO是一个瓶颈并且程序大部分时间都在等待IO时,线程解决了这个问题。在我的例子中,程序消耗了100%的cpu,io在这里可以忽略不计。我想你关心的是你对I和J的出现顺序。对吗?@gosom不是真的。我从同一行读取I(I)和J(J),我需要同步它们,但顺序并不重要。我需要一些具有持久状态的多处理工人。因此,我最终会将来自不同工作人员的结果连接起来。这其中的哪一部分实际上很慢?读取文件并构建
I
/J
,或者调用coo\u矩阵
?如果大部分时间都花在coo\u matrix
上,那么多处理
确实帮不了你。results.get()
永远不会引发队列。Empty
异常。当结果
为空时,它将被阻止。您需要使用get\u nowait()
。您在main
中的缩进似乎也关闭了。