c配置导入

时间:2015-08-02 21:33:31

标签: python profiler cprofile

我目前正在学习如何使用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上生成如此高的输出信息吗?

2 个答案:

答案 0 :(得分:4)

我不知道如何通过直接从命令行运行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}

<强>更新

您可以通过使用context manager方法派生自己的Profile类来自动化,从而使分析更容易。我没有添加一个名为enable_profiling()的方法来实现它,而是实现了它,这样你就可以在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子类,所有基类的方法(例如dump_stats())仍可供使用,如图所示。

当然,您可以采取进一步措施并添加例如一种生成统计数据并以某种自定义方式格式化的方法。

答案 1 :(得分:2)

如果稍微更改脚本,那么在不分析导入的情况下分析脚本会更容易。

test_cprofiler.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()

profiler.py

import cProfile

import test_cprofiler

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

运行方式:

python profiler.py

产生以下输出:

Fast!
Slow!
Medium!
         8 function calls in 3.498 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    3.498    3.498 <string>:1(<module>)
        1    0.000    0.000    2.998    2.998 run.py:11(slow)
        1    0.000    0.000    3.498    3.498 run.py:15(main)
        1    0.000    0.000    0.000    0.000 run.py:4(fast)
        1    0.000    0.000    0.500    0.500 run.py:7(medium)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        2    3.498    1.749    3.498    1.749 {time.sleep}
相关问题