How do you calculate program run time in python?
Asked
Active
Viewed 4.6e+01k times
5 Answers
346
Quick alternative
import timeit
start = timeit.default_timer()
#Your statements here
stop = timeit.default_timer()
print('Time: ', stop - start)

Tanya Branagan
- 551
- 1
- 12
- 21

H.Rabiee
- 4,747
- 3
- 23
- 35
-
4
-
1@diffracteD yes, UNIX EPOCH. http://docs.python.org/2/library/timeit.html#timeit.default_timer and http://www.epochconverter.com/ – H.Rabiee Mar 14 '14 at 17:48
-
5But default_timer() measures wall clock time, hence any other program will interfere with the measurement. – karzler007 Feb 23 '16 at 14:09
67
I don't know if this is a faster alternative, but I have another solution -
from datetime import datetime
start=datetime.now()
#Statements
print datetime.now()-start

nsane
- 1,715
- 4
- 21
- 31
-
1My favorite! Very simple, but I find that the final line should be 'print( datetime.now()-start )' and does not work without the parentheses. – Thomas Winckelman Jan 15 '20 at 02:08
-
6@ThomasWinckelman: At the time I wrote the answer keeping Python 2 in mind. – nsane Jan 15 '20 at 04:09
63
You might want to take a look at the timeit
module:
http://docs.python.org/library/timeit.html
or the profile
module:
http://docs.python.org/library/profile.html
There are some additionally some nice tutorials here:
http://www.doughellmann.com/PyMOTW/profile/index.html
http://www.doughellmann.com/PyMOTW/timeit/index.html
And the time
module also might come in handy, although I prefer the later two recommendations for benchmarking and profiling code performance:

JoshAdel
- 66,734
- 27
- 141
- 140
-
1Thanks! This worked great. One note for others who may be using timeit for the first time, you will need to import locally defined symbols via timeit's setup parameter. For example (if myOwnFunc was locally defined and what you wanted to time): `print timeit.timeit('myOwnFunc()', setup='from __main__ import myOwnFunc', number=1)`. Without the setup parameter, it will complain that it could not find myOwnFunc. – Landshark666 Dec 24 '12 at 04:13
6
@JoshAdel covered a lot of it, but if you just want to time the execution of an entire script, you can run it under time
on a unix-like system.
kotai:~ chmullig$ cat sleep.py
import time
print "presleep"
time.sleep(10)
print "post sleep"
kotai:~ chmullig$ python sleep.py
presleep
post sleep
kotai:~ chmullig$ time python sleep.py
presleep
post sleep
real 0m10.035s
user 0m0.017s
sys 0m0.016s
kotai:~ chmullig$

chmullig
- 13,006
- 5
- 35
- 52