I have a program say:
for i in xrange(10):
for p in xrange(10):
print i, p
I would like to be able to print the time in milliseconds that the program took to execute at the end of the program.
Run your program with python -m timeit -s 'import my_module' 'my_module.do_stuff()' to see running time information.
As per the timeit documentation, just rolling your own is a tiny bit tricky, so it's provided for you.
Here is how you can do it inside your python code although I prefer the method by @Julian, just providing this as an alternative:
from timeit import timeit
def foo():
for i in xrange(10):
for p in xrange(10):
print i, p
print timeit(setup='from __main__ import foo', stmt='foo()') # returns float of seconds taken to run
I've written a small snippet that could allow you to measure the elapsed time using a context manager. Have a look at https://github.com/BaltoRouberol/timer-context-manager
Example:
from timer import Timer
with Timer() as t:
# Some code we want to time
print t.elapsed_ms # elapsed time, in milliseconds
It uses timeit.default_timer (a platform specific timer function :time.time for Unix platforms and time.clock for Windows platforms) to measure the wall clock time of the block.
check out the time.clock() function (http://docs.python.org/library/time.html)
timeit is best for measuring runtime