分析简单 python 脚本

profiling simple python script

我正在试验 cProfile 进行分析 python applications.so 我写了一个简单的脚本,下面是我得到的结果。

def foo():
  for i in range(100000):
    print i

def bar():
  for i in range(100):
    print "bar"*i

foo()
bar()

当我 运行 上面的脚本作为 python -m profile script.py 我得到这个输出:

         7 function calls in 0.136 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        2    0.000    0.000    0.000    0.000 :0(range)
        1    0.000    0.000    0.000    0.000 :0(setprofile)
        1    0.000    0.000    0.136    0.136 lip.py:1(<module>)
        1    0.136    0.136    0.136    0.136 lip.py:1(foo)
        1    0.000    0.000    0.000    0.000 lip.py:5(bar)
        1    0.000    0.000    0.136    0.136 profile:0(<code object <module> at 0x7fae5a978a30, file "lip.py", line 1>)
        0    0.000             0.000          profile:0(profiler)

但从输出来看,似乎只有方法 foo 消耗了 0.136 s 来执行,而方法是 0.00 s bar。这是为什么?

您在 foo 中所做的工作比在 bar 中多 1000 倍。

假设他们有相同的速度,0.136 / 1000 = 0.000136对于这个显示来说这个数字太小了,而bar()的时间正好四舍五入到0.00