Monday, January 20, 2014

Python tip[6]

Tip #6

Today's tip is in response to a great question on a local Linux user group:

python -m cProfile

What it does: It'll give you a breakdown per line of how much time each operation takes to execute. Normally, profiling is best done with something like dtrace, to minimize the impact on the run time, but the original question was about figuring out the time for each operation in a python script running on the Raspberry Pi (no dtrace...).

Assuming the following script (we'll use sleep to simulate different runtime, and not call the same function either, else each would be collased under one line on the report):
from time import sleep

def x():

def y():

def z():

print("outta here")
we get:
python -m cProfile
outta here
         8 function calls in 11.009 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   11.009   11.009<module>)
        1    0.000    0.000    4.002    4.002
        1    0.000    0.000    5.005    5.005
        1    0.000    0.000    2.002    2.002
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        3   11.009    3.670   11.009    3.670 {time.sleep}


No comments: