I want to know how long it takes since I execute the code to start the timer and then the one to finish. For example, this is something I’d be looking for:
import timerlib
import urllib2
timer = timerlib.timer()
print 'Starting download now!'
timer.start()
urllib2.urlopen('http://some.site.com/100mb')
timer.stop()
print 'Downloaded 100mb in ' + str(timer.collectedtime()) + '!'
And it would output something like: Downloaded 100mb in 5m31s!
How can I do this?
If you’re just printing out a time for the convenience of the end user, not for profiling purposes, you don’t need anything fancy;
time.timereturns timestamps you can do arithmetic on and print (in fact, just floating-point seconds):But if you’re looking for profiling, you definitely want to use
timeit:As you can see, this is not nearly as clean and simple, or as flexible. But the
timeitlibrary takes care of all kinds of details that novices never think of, and experienced developers still get wrong.(Of course in real life, you never want to profile anything based on just one run, so you shouldn’t be passing
number=1. That was just to demonstrate the closest equivalent.)