【问题标题】:Profiling Python code that uses multiprocessing?分析使用多处理的 Python 代码?
【发布时间】:2013-08-11 14:16:21
【问题描述】:

我在部分 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()

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

有没有办法解决这个错误?

【问题讨论】:

    标签: python profiling cprofile


    【解决方案1】:

    据我了解,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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2019-09-06
      相关资源
      最近更新 更多