2017-10-19 199 views
0

所以我有一个函数,它只通过两个参数对几个.txt文件执行一些操作。它目前正在按预期工作,但我在近一个小时内就完成了10%的东西 - 所以需要一些时间,因为.txt文件相当大。具有两个参数的函数的多处理(池)

现在,我已经阅读了关于程序包多重处理的内容,尤其是其中的Pool段。但是,我不太清楚我如何正确使用它。

我用它来运行我的函数的代码如下:

for k, structure in enumerate(structures): 
    structure_maker(structure_path, structure) 

structure_path始终是相同的,而structures是不同值的列表,如:

structures = [1, 3, 6, 7, 8, 10, 13, 25, 27] 

所以我将如何去使用这个池进程? 至于我可以阅读我必须做一些事情,如:

from multiprocessing import Pool 

mypool = Pool(6) # Choosing how many cores I want to use 
mypool.map(structure_maker, list) 

而且list是我迷路。那应该是什么? structures列表,如果是的话,我在哪里可以放入我的structure_path

回答

1

Pool.map()函数类似于内置map()功能呢,换句话说,它适用传递给它的可迭代传递给它的第二个参数的参数给每个项目的功能。每次调用提供的函数时,它都会将该迭代中的下一个项目作为该函数的参数单一参数提供。

这种情况下的一个潜在问题是您要使用的函数structure_maker()需要两个参数。对此有不同的解决方法,但在这种情况下,由于其中一个参数始终是相同的,所以可以使用functools.partial()函数来创建只需要将第二个参数传递给它的临时函数 - 并且您可以执行此操作请致电mypool.map()

这里就是我的意思是:

from multiprocessing import Pool 

def structure_maker(structure_path, structure): 
    """ Dummy for testing. """ 
    return structure_path, structure 

if __name__ == '__main__': 

    from pprint import pprint 
    from functools import partial 

    mypool = Pool(4) 
    structure_path = 'samething' 
    structures = [1, 3, 6, 7, 8, 10, 13, 25, 27] 
    results = mypool.map(partial(structure_maker, structure_path), structures) 
    pprint(results) 

输出:

[('samething', 1), 
('samething', 3), 
('samething', 6), 
('samething', 7), 
('samething', 8), 
('samething', 10), 
('samething', 13), 
('samething', 25), 
('samething', 27)] 
0

您可能需要制作并解压缩tuple

def structure_maker_proxy(args): 
    structure_path, structure = args 
    structure_maker(structure_path, structure) 


from multiprocessing import Pool 

mypool = Pool(6) # Choosing how many cores I want to use 

lis = [(structure_path, struct) for struct in structures] 
mypool.map(structure_maker_proxy, lis) 
相关问题