How do you calculate program run time in python?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Quick alternative
import timeit
start = timeit.default_timer()
#Your statements here
stop = timeit.default_timer()
print('Time: ', stop - start)
Method 2
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
Method 3
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:
http://docs.python.org/library/time.html
Method 4
@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$
Method 5
see this:
Python – time.clock() vs. time.time() – accuracy?
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0