A simple way to time a small bits of Python code

Thursday, February 19th, 2009
Advertisement

Subscribe.
Enter your email:

A simple way to time a small bits of Python code is by using the time module. Please look at the example below.

>>> from time import time, sleep
>>> def f(x):
    '''
    Does nothing. Sleep for x seconds.
    '''
    sleep(x)

>>> time1 = time(); f(5); print('Run in {0:f} seconds.'.format(time()-time1))
Run in 5.000000 seconds.

Code break down:

In the above example, we want to measure how long will the function f() run.

  1. Import the time module.
    from time import time, sleep
  2. Get the current time.
    time1 = time()
  3. Run the function, get the current time, print the time elapsed.
    f(5)
    print('Run in {0:f} seconds.'.format(time()-time1))
If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>