Search code examples
pythonperformancecprofile

profiling simple python script


i was experimenting with cProfile for profiling python applications.so i wrote a simple script and below is the results that i have.

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

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

foo()
bar()

When i run the above script as python -m profile script.py i get this output:

         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)

but from the ouptut is seems only method foo consumed 0.136 s to excute while it was 0.00 s for method bar. why is that?


Solution

  • You are doing 1000x more work in foo than in bar.

    Assuming they had the same speed, 0.136 / 1000 = 0.000136 which is too small of a number for this display, and bar()'s time just rounds to 0.00.