分析使用多处理的Python代码?

时间:2013-08-09 15:23:48

标签: python profiling cprofile

我在gui代码的一部分中设置了一个简单的生产者消费者模式。我试图仅描述特定的消费者部分,看看是否有任何优化机会。但是,当尝试使用python -m cProfile -o out.txt myscript.py运行代码时,我收到了来自Python的pickle模块的错误。

  File "<string>", line 1, in <module>
  File "c:\python27\lib\multiprocessing\forking.py", line 374, in main
    self = load(from_parent)
  File "c:\python27\lib\pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "c:\python27\lib\pickle.py", line 858, in load
    dispatch[key](self)
  File "c:\python27\lib\pickle.py", line 880, in load_eof
    raise EOFError
EOFError

代码中的基本模式是

class MyProcess(multiprocessing.Process):
    def __init__(self, in_queue, msg_queue):
        multiprocessing.Process.__init__(self)
        self.in_queue = in_queue
        self.ext_msg_queue = msg_queue
        self.name == multiprocessing.current_process().name

    def run(self):
        ## Do Stuff with the queued items

这通常是从GUI端提供的任务,但出于测试目的,我将其设置如下。

if __name__ == '__main__':

    queue = multiprocessing.Queue()
    meg_queue = multiprocessing.Queue()
    p = Grabber(queue)
    p.daemon = True
    p.start()
    time.sleep(20)
    p.join()

但是在尝试启动脚本时,我收到上面的错误消息。

有没有解决错误的方法?

1 个答案:

答案 0 :(得分:3)

据我了解,cProfile模块在​​命令行上与multiprocessing不兼容。 (见Python multiprocess profiling。)

解决此问题的一种方法是从代码中运行探查器 - 特别是,您需要为池中的每个进程设置不同的探查器输出文件。您可以通过拨打cProfile.runctx('a+b', globals(), locals(), 'profile-%s.out' % process_name)来轻松完成此操作。

http://docs.python.org/2/library/profile.html#module-cProfile