gpt4 book ai didi

python - 多处理比单个(正常)处理花费的时间更长

转载 作者:行者123 更新时间:2023-12-03 13:01:59 30 4
gpt4 key购买 nike

怎么来的multi使用多处理池对多个“进程”上的数据进行分段和处理的函数比仅调用 map 慢(8 秒)。功能(6 秒)?

from multiprocessing import Pool
import timeit


def timer(function):
def new_function():
start_time = timeit.default_timer()
function()
elapsed = timeit.default_timer() - start_time
print('Function "{name}" took {time} seconds to complete.'.format(name=function.__name__, time=elapsed))
return new_function


def cube(n):
return n*n*n

nums = range(20000000)
if __name__ == '__main__':
@timer
def multi():

pool = Pool()
res = pool.map(cube,nums)
pool.close()
pool.join()

@timer
def test():
a = map(cube,nums)

multi()
test()

最佳答案

因为pool.map背后的所有调度逻辑造成开销。
多处理总是会产生某种开销,这在很大程度上取决于其底层实现。
您在这里运行了许多非常简单的任务,因此线程逻辑造成的开销无法通过并行执行的增益来补偿。尝试用较少数量的 cpu 密集型任务进行相同的测试,您应该看到不同的结果。
例子
请参阅此修改后的测试。在这里,我们有一个愚蠢的cubes计算 n^3 的函数1000 次。

from multiprocessing import Pool
import timeit


def timer(function):
def new_function():
start_time = timeit.default_timer()
function()
elapsed = timeit.default_timer() - start_time
print('Function "{name}" took {time} seconds to complete.'.format(name=function.__name__, time=elapsed))
return new_function


def cubes(n):
for _ in range(999):
n * n * n
return n * n * n

nums = range(20000)
if __name__ == '__main__':
@timer
def multi():
pool = Pool()
res = pool.map(cubes, nums)
pool.close()
pool.join()

@timer
def test():
# On Python 3, simply calling map() returns an iterator
# tuple() collects its values for timing
a = tuple(map(cubes, nums))

multi()
test()
我们现在看到多处理正在改善我们的时间安排:
Function "multi" took 0.6272498000000001 seconds to complete.
Function "test" took 2.130454 seconds to complete.

关于python - 多处理比单个(正常)处理花费的时间更长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66130552/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com