As other timing recipes have mentioned, the timeit module could be easier to work with. Sometimes, I just want to bracket a particular script with start, stop, and duration timing info. The following module (which I named "timing.py") is about as non-intrusive as you can get - just import the module.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | # timing.py
# by Paul McGuire, May, 2008
#
import atexit
import time
__all__ = ""
def secondsToStr(t):
rediv = lambda ll,b : list(divmod(ll[0],b)) + ll[1:]
return "%d:%02d:%02d.%03d" % \
tuple(reduce(rediv,[[t*1000,],1000,60,60]))
def printTimeMarker(s,printElapsed=False):
def printCurrentTime():
print
print "="*40
print s
print "%d/%02d/%02d %02d:%02d:%02d" % time.localtime()[:6]
if printElapsed:
print "Elapsed time:", secondsToStr(time.time() - startTime)
print "="*40
print
return printCurrentTime
atexit.register(printTimeMarker("Program end",True))
printTimeMarker("Program start")()
startTime = time.time()
|
If you want to get just simple overall statistics for running a script, you can just add this script to your Python site-packages directory, and then at the top of your script (or at the top of your "if __name__=='__main__':" block), add: <pre> import timing </pre>
When you run your script, importing this module will display a start time header, and register an atexit method that will display the end/elapsed time footer.