如何让 `cProfile.run` 记录调用 `str` 所消耗的时间? [英] How do I get `cProfile.run` to log time consumed by calls to `str`?
问题描述
我正在尝试分析一些对 str
进行大量调用的代码的性能,看看我是否可以从替换其他方法来使用 str
中受益>,但我无法让 cProfile.run
显示对 str
的调用消耗了多少时间.
I'm trying to analyze the performance of some code that makes a lot of calls to str
to see if I can benefit from substituting other approaches for the use of str
, but I can't get cProfile.run
to show me how much time calls to str
are consuming.
例如,如果我测试(废话)代码
For example if I test the (nonsense) code
def foo(n):
x = ''
for i in range(n):
x += str(n)
x = str(len(str(n)))
使用 cProfile.run('foo(1000000)')
我没有提到必须对 str
进行的许多调用:
with cProfile.run('foo(1000000)')
I get no mention of the many calls that must have been made to str
:
1000004 function calls in 1.163 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.163 1.163 <string>:1(<module>)
1 1.046 1.046 1.163 1.163 example.py:172(foo)
1000000 0.081 0.000 0.081 0.000 {len}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.036 0.036 0.036 0.036 {range}
如何让 cProfile.run
显示对 str
的调用的统计信息?
How do I get cProfile.run
to show statistics for calls to str
?
推荐答案
我不知道为什么它不显示对 str
的调用,但是您可以轻松绕过这种行为(为了仅用于分析),通过覆盖内置的 str
.
I'm not sure why it does not display the calls to str
, but you can easily bypass this behavior (for the sake of profiling only), by overriding the builtin str
.
只需将此代码添加到脚本的顶部,或者在调用 cProfile
之前:
Simply add this code at the top of your script, or before invoking cProfile
:
orig_str = __builtin__.str
def mystr(*a, **kw): return orig_str(*a, **kw)
__builtin__.str = mystr
这可能与原始代码不完全兼容(例如,如果您的代码中有一些地方可以执行诸如 if type(x) == str
之类的事情),但希望它可以在您的案例.
This might not be completely compatible with the original code (e.g. if you have places in your code which do things like if type(x) == str
), but hopefully it would work in your case.
这篇关于如何让 `cProfile.run` 记录调用 `str` 所消耗的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!