【问题标题】:How do I get `cProfile.run` to log time consumed by calls to `str`?如何让`cProfile.run`记录调用`str`所消耗的时间?
【发布时间】:2013-11-30 04:12:58
【问题描述】:

我正在尝试分析一些对str 进行大量调用的代码的性能,以查看是否可以从使用str 的其他方法中受益,但我无法获得@987654323 @ 告诉我调用str 花费了多少时间。

例如,如果我测试(废话)代码

def foo(n):
    x = ''
    for i in range(n):
        x += str(n)
        x = str(len(str(n)))

对于cProfile.run('foo(1000000)'),我没有提到必须拨打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 的统计信息?

【问题讨论】:

    标签: python string python-2.7 profiling


    【解决方案1】:

    我不确定为什么它不显示对 str 的调用,但您可以通过覆盖内置的 str 轻松绕过此行为(仅用于分析)。

    只需将此代码添加到脚本顶部,或在调用 cProfile 之前:

    orig_str = __builtin__.str
    def mystr(*a, **kw): return orig_str(*a, **kw)
    __builtin__.str = mystr
    

    这可能与原始代码不完全兼容(例如,如果您的代码中有一些地方可以执行if type(x) == str 之类的操作),但希望它适用于您的情况。

    【讨论】:

      猜你喜欢
      • 2020-10-20
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多