【问题标题】:Multiprocessing taking longer than single (normal) processing多处理比单(正常)处理花费更长的时间
【发布时间】:2021-02-10 17:24:36
【问题描述】:

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

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()

【问题讨论】:

    标签: python python-3.x multithreading multiprocessing


    【解决方案1】:

    因为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.
    

    【讨论】:

      猜你喜欢
      • 2013-11-09
      • 2018-08-18
      • 1970-01-01
      • 2017-01-24
      • 2021-02-14
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多