Simplified timeit

C

C. Barnes

I've been avoiding the timeit module because it seems
overly complicated. I finally coded my own function
(named timeit :), which has the following benefits:

1. Simple
2. Figures out how many times to evaluate the
callable passed to it.

Here's the code:

from time import clock

def timeit(f, time=0.5):
"""Calls f many times to determine the average time
to execute f.
Usually accurate to within 3%."""
count = 1
while True:
start = clock()
for i in range(count): f()
end = clock()
T = end - start
if T >= time: break
count *= 2
return T / count

Example:

from math import *

def f(x): return x * x - cos(x)
def g(): return f(1.0)

t = timeit(g)
print 'Time to execute f: ', t
print 'Calls to f per second: ', 1.0/t

PS: Try repeating this benchmark with psyco. I get a
70x increase in speed.

Connelly Barnes





__________________________________
Do you Yahoo!?
Friends. Fun. Try the all-new Yahoo! Messenger.
http://messenger.yahoo.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top