分析python多处理池

Fra*_*rth 7 python profiling pool multiprocessing

我正在尝试在多处理池中的每个进程上运行cProfile.runctx(),以了解我的源中的多处理瓶颈.这是我正在尝试做的简化示例:

from multiprocessing import Pool
import cProfile

def square(i):
    return i*i

def square_wrapper(i):
    cProfile.runctx("result = square(i)",
        globals(), locals(), "file_"+str(i))
    # NameError happens here - 'result' is not defined.
    return result

if __name__ == "__main__":
    pool = Pool(8)
    results = pool.map_async(square_wrapper, range(15)).get(99999)
    print results
Run Code Online (Sandbox Code Playgroud)

不幸的是,尝试在探查器中执行"result = square(i)"不会影响调用它的范围内的"结果".我怎样才能完成我想在这里做的事情?

Cat*_*lus 6

试试这个:

def square_wrapper(i):
    result = [None]
    cProfile.runctx("result[0] = square(i)", globals(), locals(), "file_%d" % i)
    return result[0]
Run Code Online (Sandbox Code Playgroud)

  • +1; 这工作,但似乎相当hacky.你能解释一下它的工作原理吗? (2认同)
  • 我猜 'result = square(i)' 只是在 cProfile.runctx 范围内(或它执行代码的任何地方)创建了一个新引用,而旧的引用完好无损。在 runctx 之前使用“全局结果”,并且在内部使用“全局结果;结果 = square(i)”(或“globals()['result'] = square(i)”)也可以。 (2认同)