How do I get time of a Python program's execution?
I put this
timing.py module into my own
site-packages directory, and just insert
import timing at the top of my module:
import atexitfrom time import clockdef secondsToStr(t): return "%d:%02d:%02d.%03d" % \ reduce(lambda ll,b : divmod(ll,b) + ll[1:], [(t*1000,),1000,60,60])line = "="*40def log(s, elapsed=None): print line print secondsToStr(clock()), '-', s if elapsed: print "Elapsed time:", elapsed print line printdef endlog(): end = clock() elapsed = end-start log("End Program", secondsToStr(elapsed))def now(): return secondsToStr(clock())start = clock()atexit.register(endlog)log("Start Program")
I can also call
timing.log from within my program if there are significant stages within the program I want to show. But just including
import timing will print the start and end times, and overall elapsed time. (Forgive my obscure
secondsToStr function, it just formats a floating point number of seconds to hh:mm:ss.sss form.)
In Linux or Unix:
$ time python yourprogram.py
In Windows, see this StackOverflow question: How do I measure execution time of a command on the Windows command line?
For more verbose output,
$ time -v python yourprogram.py Command being timed: "python3 yourprogram.py" User time (seconds): 0.08 System time (seconds): 0.02 Percent of CPU this job got: 98% Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.10 Average shared text size (kbytes): 0 Average unshared data size (kbytes): 0 Average stack size (kbytes): 0 Average total size (kbytes): 0 Maximum resident set size (kbytes): 9480 Average resident set size (kbytes): 0 Major (requiring I/O) page faults: 0 Minor (reclaiming a frame) page faults: 1114 Voluntary context switches: 0 Involuntary context switches: 22 Swaps: 0 File system inputs: 0 File system outputs: 0 Socket messages sent: 0 Socket messages received: 0 Signals delivered: 0 Page size (bytes): 4096 Exit status: 0