你如何让 Python 分析器工作? [英] How do you get the Python profiler to work?

查看:35
本文介绍了你如何让 Python 分析器工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照此处的说明进行操作:http://docs.python.org/2/library/profile.html#module-cProfile

I'm trying to follow the instructions here: http://docs.python.org/2/library/profile.html#module-cProfile

具体来说,这部分:

import cProfile, pstats, io
pr = cProfile.Profile()
pr.enable()
... do something ...
pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s)
ps.print_results()

我已经确定 print_results 不是 Stats 类的真正方法,它似乎也不存在于任何地方.这是我当前的代码:

I've already determined that print_results is not a real method of the Stats class, nor does it seem to really exist anywhere. Here is my current code:

import cProfile, pstats, io
def foo(request):
    pr = cProfile.Profile()
    pr.enable()
    pass
    pr.disable()
    s = io.StringIO()
    ps = pstats.Stats(pr, stream = s)
    f = open('/profstats', 'a')
    ps.print_stats()
    f.write(s.getvalue())
    s.close()
    f.close()

目前的结果是:/inspection-summary/处的类型错误需要 unicode 参数,得到 'str'

Current result is: TypeError at /inspection-summary/ unicode argument expected, got 'str'

(输出看起来像这样,因为我使用 Django 来调用有问题的代码).

(Output looks like this because I am using Django to call the code in question).

那么有谁知道我怎样才能让分析器实际工作?我只是希望它像预期的那样进行分析,然后将结果打印到文件中,以便稍后在执行后查看结果.我可以让 dump_stats 工作,但它产生的文件是垃圾.

So does anyone know how I can get the profiler to actually, well, work? I just want it to profile like it's supposed to, then print the results to a file so I can view the results later after execution. I can get dump_stats to work, but the file it produces is garbage.

推荐答案

确实,profile/pstats 模块的 API 看起来相当特别.我认为行 ps.print_results() 应该是一个通用的,即它应该写为 ps.call_some_methods_to_print_the_result() ,但这确实不清楚.至于dump_stats(),它实际上保存了一个二进制文件,以后可以重新加载.

Indeed, the API of the profile/pstats modules look rather ad-hoc. I think the line ps.print_results() is supposed to be a generic one, i.e. it should be written as ps.call_some_methods_to_print_the_result(), but this is not clear indeed. As for dump_stats() it actually saves a binary file that can be reloaded later.

这是一个对我有用的例子:

Here is an example that works for me:

import cProfile, pstats
pr = cProfile.Profile()
pr.enable()
...
pr.disable()

f = open('x.prof', 'a')
sortby = 'cumulative'
pstats.Stats(pr, stream=f).strip_dirs().sort_stats(sortby).print_stats()
f.close()

sortby 的有效值为:调用、累积、文件、行、模块、名称、nfl(对于名称/文件/行)、pcalls、stdname、时间.

Valid values ofsortby are: calls, cumulative, file, line, module, name, nfl (for name/file/line), pcalls, stdname, time.

这篇关于你如何让 Python 分析器工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆