How do you calculate program run time in python?

PythonTimeRuntime

Python Problem Overview


How do you calculate program run time in python?

Python Solutions


Solution 1 - Python

Quick alternative

import timeit

start = timeit.default_timer()

#Your statements here

stop = timeit.default_timer()

print('Time: ', stop - start)  

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

@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$ 

Solution 5 - Python

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfeiskyView Question on Stackoverflow
Solution 1 - PythonH.RabieeView Answer on Stackoverflow
Solution 2 - PythonJoshAdelView Answer on Stackoverflow
Solution 3 - PythonnsaneView Answer on Stackoverflow
Solution 4 - PythonchmulligView Answer on Stackoverflow
Solution 5 - Pythonanta40View Answer on Stackoverflow