如何在python中并行化for循环?

时间:2018-10-25 20:22:20

标签: python multiprocessing networkx python-multiprocessing

我写了一个函数来分析Python中的图形(使用NetworkX),我需要运行500次,这需要很长时间。我尝试使用来自多处理程序的Pool对其进行并行化,但是即使我将范围设置为较小的值(如5而不是500),它也使计算机崩溃了。有人可以看一下吗?谢谢!

import numpy as np
import random as rn
import networkx as nx
import operator
import bcCalcs
from multiprocessing import Process

n1 = 100
n2 = 200
p = 1/2
q = 1/4000

percent = 0

def baInter():

    global percent
    icCount = .1*(n1+n2)
    while icCount >= (.1*(n1+n2)):

        ba = bcCalcs.baModel(n1, n2, 4, 4, q)

        g = nx.from_numpy_matrix(ba)

        globalBC = nx.betweenness_centrality(g, normalized = False)
        globalBCsorted = bcCalcs.sortBC(globalBC, 1)
        interCommNodes = bcCalcs.inter_comm_nodes(ba, n1)
        icCount = len(interCommNodes)


    for node in globalBCsorted:
        if node[0] in interCommNodes:
            percent = percent + 1

    print("x")        

if __name__ == "__main__":

    procs = []

    for i in range(500):
        proc = Process(target=baInter)
        procs.append(proc)
        proc.start()

    for proc in procs:
        proc.join

percent = 100*(percent/500)

print(percent)

0 个答案:

没有答案