The Python Oracle

How do you calculate program run time in python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping

--

Chapters
00:00 Question
00:17 Accepted answer (Score 63)
00:58 Answer 2 (Score 342)
01:12 Answer 3 (Score 67)
01:28 Answer 4 (Score 6)
01:56 Thank you

--

Full question
https://stackoverflow.com/questions/5622...

Accepted answer links:
http://docs.python.org/library/timeit.ht...
http://docs.python.org/library/profile.h...
http://www.doughellmann.com/PyMOTW/profi...
http://www.doughellmann.com/PyMOTW/timei...
http://docs.python.org/library/time.html

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #time #runtime

#avk47



ANSWER 1

Score 351


Quick alternative

import timeit

start = timeit.default_timer()

#Your statements here

stop = timeit.default_timer()

print('Time: ', stop - start)  



ACCEPTED ANSWER

Score 64


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




ANSWER 3

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



ANSWER 4

Score 4


see this: Python - time.clock() vs. time.time() - accuracy?