How to find statistics and execution times of code in python

advertisements

I am working on python and came across some concept of finding the statistics and execution time of the code

Suppose i had the following code

from time import gmtime, strftime
import timeit

def calculation():
     a = 2
     b = 3
     res = a + b
     return  res

if 'name' == 'main' :
    exec_time = timeit.timeit(calculation)
    print exec_time

result:

0.2561519145965576

So from the above code i am able to find the execution time of the code , but how to find the statistics of the code in python ?

Finally my intention is below points

  1. How to find the statistics of the code in python
  2. How to find the execution time of the entire code in python
  3. What actually meant statistics of the code ?

Edited Code:

For example i had the above code in the file test.py

Now i had run the above file with the command below

python -m cProfile test.py

Result :

sh-4.2$ python -m cProfile test.py
         4 function calls in 0.001 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    0.001    0.001 test.py:1(<module>)
        1    0.000    0.000    0.000    0.000 timeit.py:105(Timer)
        1    0.001    0.001    0.001    0.001 timeit.py:53(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

So i need something like this when i run the above code, what i am trying is to write this functionality of printing statistics inside the file test.py instead of running the file with command python -m cProfile test.py from terminal.

At least i want to find the statistics and execution time of the function calculation() when the file runs because in real the function calculation has big functionality that performs some operation.


It appears what you are asking is how to the programmatic interface for the timeit module. That is documented here. You'll need a sample set to calculate statistics, such min, max, average, etc. from, which means running calculate numerous times through the repeat method of the Timeit class included in the timeit module.

For example:

timer = timeit.Timer(calculation)
results = timer.timeit(10000)