带有导入的cProfile

问题描述 投票:4回答:2

我目前正在学习如何使用cProfile,但我有一些疑问。

我目前正在尝试分析以下脚本:

import time

def fast():
    print("Fast!")

def slow():
    time.sleep(3)
    print("Slow!")

def medium():
    time.sleep(0.5)
    print("Medium!")

fast()
slow()
medium()

我执行命令python -m cProfile test_cprofile.py,结果如下:

Fast!
Slow!
Medium!
     7 function calls in 3.504 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    3.504    3.504 test_cprofile.py:1(<module>)
    1    0.000    0.000    0.501    0.501 test_cprofile.py:10(medium)
    1    0.000    0.000    0.000    0.000 test_cprofile.py:3(fast)
    1    0.000    0.000    3.003    3.003 test_cprofile.py:6(slow)
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
    2    3.504    1.752    3.504    1.752 {time.sleep}

但是,当我使用顶部的pylab导入(import pylab)编辑脚本时,cProfile的输出非常大。我尝试使用python -m cProfile test_cprofile.py | head -n 10限制行数,但是收到以下错误:

Traceback (most recent call last):
File "/home/user/anaconda/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/home/user/anaconda/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/user/anaconda/lib/python2.7/cProfile.py", line 199, in <module>
main()
File "/home/user/anaconda/lib/python2.7/cProfile.py", line 192, in main
runctx(code, globs, None, options.outfile, options.sort)
File "/home/user/anaconda/lib/python2.7/cProfile.py", line 56, in runctx
result = prof.print_stats(sort)
File "/home/user/anaconda/lib/python2.7/cProfile.py", line 81, in print_stats
pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats()
File "/home/user/anaconda/lib/python2.7/pstats.py", line 360, in print_stats
self.print_line(func)
File "/home/user/anaconda/lib/python2.7/pstats.py", line 438, in print_line
print >> self.stream, c.rjust(9),
IOError: [Errno 32] Broken pipe

有人可以帮助解决与这种情况类似的正确程序吗?在这种情况下,我们有一个import pylab或另一个模块会在cProfile上生成如此高的输出信息?

python profiler cprofile
2个回答
5
投票

我不知道如何通过直接从命令行运行cProfile模块来执行选择性分析,就像您想要的一样。

但是,您可以通过修改代码以显式import该模块来完成此操作,但是您必须自己做所有事情。这是对示例代码的处理方式:

((注:以下代码与Python 2和3兼容。)

from cProfile import Profile
from pstats import Stats
prof = Profile()

prof.disable()  # i.e. don't time imports
import time
prof.enable()  # profiling back on

def fast():
    print("Fast!")

def slow():
    time.sleep(3)
    print("Slow!")

def medium():
    time.sleep(0.5)
    print("Medium!")

fast()
slow()
medium()

prof.disable()  # don't profile the generation of stats
prof.dump_stats('mystats.stats')

with open('mystats_output.txt', 'wt') as output:
    stats = Stats('mystats.stats', stream=output)
    stats.sort_stats('cumulative', 'time')
    stats.print_stats()

[mystats_output.txt文件之后的内容:

Sun Aug 02 16:55:38 2015    mystats.stats

         6 function calls in 3.522 seconds

   Ordered by: cumulative time, internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        2    3.522    1.761    3.522    1.761 {time.sleep}
        1    0.000    0.000    3.007    3.007 cprofile-with-imports.py:15(slow)
        1    0.000    0.000    0.515    0.515 cprofile-with-imports.py:19(medium)
        1    0.000    0.000    0.000    0.000 cprofile-with-imports.py:12(fast)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

更新:

您可以使用Profile方法派生您自己的context manager类来使事情自动化,从而使启用配置文件更加容易。我已经实现了它,而不是添加一个像enable_profiling()这样的名称的方法,以便您可以在with语句中调用类实例。每当退出with语句控制的上下文时,分析将自动关闭。

这里是课程:

with

使用它代替库存from contextlib import contextmanager from cProfile import Profile from pstats import Stats class Profiler(Profile): """ Custom Profile class with a __call__() context manager method to enable profiling. """ def __init__(self, *args, **kwargs): super(Profile, self).__init__(*args, **kwargs) self.disable() # Profiling initially off. @contextmanager def __call__(self): self.enable() yield # Execute code to be profiled. self.disable() 对象看起来像这样:

Profile

因为它是profiler = Profiler() # Create class instance. import time # Import won't be profiled since profiling is initially off. with profiler(): # Call instance to enable profiling. def fast(): print("Fast!") def slow(): time.sleep(3) print("Slow!") def medium(): time.sleep(0.5) print("Medium!") fast() slow() medium() profiler.dump_stats('mystats.stats') # Stats output generation won't be profiled. with open('mystats_output.txt', 'wt') as output: stats = Stats('mystats.stats', stream=output) stats.strip_dirs().sort_stats('cumulative', 'time') stats.print_stats() # etc... 子类,所以所有基类的方法,例如Profile都仍然可以使用,如图所示。

当然,您可以将其进一步加上例如一种生成统计信息并以自定义方式格式化它们的方法。


2
投票

如果您稍稍更改脚本,则无需对导入进行概要分析就可以更轻松地分析脚本。

test_cprofiler.py

dump_stats()

profiler.py

import time
import pylab

def fast():
    print("Fast!")

def slow():
    time.sleep(3)
    print("Slow!")

def medium():
    time.sleep(0.5)
    print("Medium!")

def main():
    fast()
    slow()
    medium()

if __name__ == "__main__":
    main()

运行方式:

import cProfile

import test_cprofiler

cProfile.run("test_cprofiler.main()")

将产生以下输出:

python profiler.py
© www.soinside.com 2019 - 2024. All rights reserved.