0

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.

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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.

Comments

0

check out the time.clock() function (http://docs.python.org/library/time.html)

2 Comments

timeit is best for measuring runtime
How did I not know this existed? I've always made my own. Thanks, and +1 for the other answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.