【问题标题】:Create a copy of an object rather that reinitialising inside of a new multiprocessing process创建对象的副本,而不是在新的多处理进程中重新初始化
【发布时间】:2012-04-07 14:26:26
【问题描述】:

这段代码显示了我正在尝试做的事情的结构。

import multiprocessing
from foo import really_expensive_to_compute_object

## Create a really complicated object that is *hard* to initialise.
T = really_expensive_to_compute_object(10) 

def f(x):
  return T.cheap_calculation(x)

P = multiprocessing.Pool(processes=64)
results = P.map(f, range(1000000))

print results

问题在于,每个进程一开始就花费大量时间重新计算 T,而不是使用计算一次的原始 T。有没有办法防止这种情况? T 有一个快速(深度)复制方法,那么我可以让 Python 使用它而不是重新计算吗?

【问题讨论】:

    标签: python copy multiprocessing deep-copy


    【解决方案1】:

    multiprocessing 文档suggests

    将资源显式传递给子进程

    所以你的代码可以重写成这样的:

    import multiprocessing
    import time
    import functools
    
    class really_expensive_to_compute_object(object):
        def __init__(self, arg):
            print 'expensive creation'
            time.sleep(3)
    
        def cheap_calculation(self, x):
            return x * 2
    
    def f(T, x):
        return T.cheap_calculation(x)
    
    if __name__ == '__main__':
        ## Create a really complicated object that is *hard* to initialise.
        T = really_expensive_to_compute_object(10)
        ## helper, to pass expensive object to function
        f_helper = functools.partial(f, T)
        # i've reduced count for tests 
        P = multiprocessing.Pool(processes=4)
        results = P.map(f_helper, range(100))
    
        print results
    

    【讨论】:

      【解决方案2】:

      为什么不让f 使用T 参数而不是引用全局,然后自己进行复制?

      import multiprocessing, copy
      from foo import really_expensive_to_compute_object
      
      ## Create a really complicated object that is *hard* to initialise.
      T = really_expensive_to_compute_object(10) 
      
      def f(t, x):
        return t.cheap_calculation(x)
      
      P = multiprocessing.Pool(processes=64)
      results = P.map(f, (copy.deepcopy(T) for _ in range(1000000)), range(1000000))
      
      print results
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-13
        • 2016-04-02
        • 1970-01-01
        • 2012-04-26
        相关资源
        最近更新 更多