views:

8469

answers:

6

I'm just trying to time a piece of code. The pseudocode looks like:

start = get_ticks()
do_long_code()
print "It took " + (get_ticks() - start) + " seconds."

How does this look in Python?

More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?

+8  A: 

What you need is time() function from time module:

import time
start = time.time()
do_long_code()
print "it took", time.time() - start, "seconds."

You can use timeit module for more options though.

blackwing
+1  A: 
import datetime

start = datetime.datetime.now()
do_long_code()
finish = datetime.datetime.now()
delta = finish - start
print delta.seconds

From midnight:

import datetime

midnight = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
now = datetime.datetime.now()
delta = now - midnight
print delta.seconds
Harley
+1  A: 

The time module in python gives you access to the clock() function, which returns time in seconds as a floating point.

Different systems will have different accuracy based on their internal clock setup (ticks per second) but it's generally at least under 20milliseconds, and in some cases better than a few microseconds.

Adam Davis
A: 

What platform do You use?

There are some timer tricks on Windows.

maxp
what tricks? besides using time.clock() instead of time.time()
Corey Goldberg
+2  A: 

In the time module, there are two timing functions: time and clock. time gives you "wall" time, if this is what you care about.

However, the python docs say that clock should be used for benchmarking. Note that clock behaves different in separate systems:

  • on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with "resolution typically better than a microsecond". It has no special meaning, it's just a number (it starts counting the first time you call clock in your process).
    # ms windows
    t0= time.clock()
    do_something()
    t= time.clock() - t0 # t is wall seconds elapsed (floating point)
  • on *nix, clock reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code:
    # linux
    t0= time.clock()
    do_something()
    t= time.clock() - t0 # t is CPU seconds elapsed (floating point)

Apart from all that, the timeit module has the Timer class that is supposed to use what's best for benchmarking from the available functionality.

¹ unless threading gets in the way…

ΤΖΩΤΖΙΟΥ
+1  A: 

This thread is about Python timing accuracy and seems relevant

http://stackoverflow.com/questions/85451/python-timeclock-vs-timetime-accuracy

Corey Goldberg