Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure script running time in Python [duplicate]

I've had this question for a long time, and I have searched for an answer in several places, without success...

My question: How to measure the time that a given script takes to fully complete?

Imagine I had this silly script to calculate the sum of all the numbers from 0 to 10^12:

x = 0
for i in range(pow(10,12)):
    x += i
print(x)

How could I know how much time it took my PC to complete that?

Thanks in advance, RSerrao

like image 819
RGS Avatar asked Jan 01 '14 23:01

RGS


3 Answers

You can use the python profiler cProfile to measure CPU time and additionally how much time is spent inside each function and how many times each function is called. This is very useful if you want to improve performance of your script without knowing where the bottlenecks are. This answer to another SO question is pretty good. It's always good to have a look in the docs too.

Here's an example how to profile a script using cProfile from a command line:

$ python -m cProfile euler048.py

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}
like image 125
jacwah Avatar answered Oct 21 '22 04:10

jacwah


I already know you can do one clever thing:

import time
# at the beginning:
start_time = time.time()

# at the end of the program:
print("%f seconds" % (time.time() - start_time))

It is not 100% accurate, but it is quite good for my purposes

like image 43
RGS Avatar answered Oct 21 '22 06:10

RGS


If you are looking for a useful one-liner and are using IPython then %timeit magic function may be useful (This has not been mentioned on the linked post so adding it for the sake of completeness):

%timeit [x for x in range(1000)]

Gives (on my machine):

10000 loops, best of 3: 37.1 µs per loop

In the case of your script, I would define a function first:

def sumx(y,z):
    x = 0
    for i in range(pow(y,z)):
        x += 1
    print(x)

Then do:

%timeit sumx(5,7)

Which gives:

100 loops, best of 3: 4.85 ms per loop
like image 20
Matt Avatar answered Oct 21 '22 06:10

Matt