Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中正确地多处理一个函数_Python_Multithreading_Parallel Processing_Multiprocessing_Python Multiprocessing - Fatal编程技术网

如何在python中正确地多处理一个函数

如何在python中正确地多处理一个函数,python,multithreading,parallel-processing,multiprocessing,python-multiprocessing,Python,Multithreading,Parallel Processing,Multiprocessing,Python Multiprocessing,我有一个脚本,它包含大量CPU绑定函数,循环遍历列表,我希望它使用多处理 脚本看起来像 ... do stuff function_result = my_heavy_function() ... do stuff after i get function_result 在阅读了一些关于多线程和多处理的内容后,我尝试了 import concurrent.futures ... do stuff with concurrent.futures.ProcessPoolEx

我有一个脚本,它包含大量CPU绑定函数,循环遍历列表,我希望它使用多处理

脚本看起来像

... do stuff
    
function_result = my_heavy_function()

... do stuff after i get function_result
在阅读了一些关于多线程和多处理的内容后,我尝试了

import concurrent.futures

... do stuff
    
with concurrent.futures.ProcessPoolExecutor() as executor:
    executor.map(my_heavy_function, my_list)

... do stuff after i get function_result
但它比我的脚本的默认版本花费了~分钟的时间,默认版本没有使用并行的东西。(为什么,如果你能向我解释的话,祝福你)

所以我所需要的就是尽快得到这个函数的结果,然后以“正常的节奏”处理这个结果。
是否有可能以这种方式使用多处理,或者我做错了什么?

不确定您的重载函数到底是什么样子的,但您可以尝试将列表拆分成块,并将其传递给工作人员,如图所示:。我认为,
ProcessPoolExecutor.map
可能只是并行多次运行您的函数……我认为ProcessPoolExecutor的作用与multiprocessing.Pool.map相同,正如您所说,它将列表分块()嗯,您是对的。这个主题/答案中的一些技巧如何?似乎他们在员工池中使用了一个
Manager()
,这有一些开销,但我链接的答案可能是性能。如果您发布了函数的实际操作,可能会有所帮助,因为这可能是相关的?@Sparrow1029我的函数将列表作为参数,并对其元素进行了大量计算。正如我从文档中了解到的,不管函数具体做什么,其主要思想是将列表分成块,并在不同的线程/进程中使用它们,而不是一次迭代整个过程。这就是我想要做的。该线程与我的问题无关,但无论如何谢谢你)