Simplified timeit

Discussion in 'Python' started by C. Barnes, Jun 8, 2004.

  1. C. Barnes

    C. Barnes Guest

    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/
     
    C. Barnes, Jun 8, 2004
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Grey

    simplified chinese encoding

    Grey, Apr 20, 2004, in forum: ASP .Net
    Replies:
    0
    Views:
    518
  2. Guest
    Replies:
    0
    Views:
    412
    Guest
    Jun 24, 2005
  3. Wandy Tang
    Replies:
    4
    Views:
    4,539
    Roedy Green
    Jul 20, 2004
  4. Connelly Barnes

    Simplified timeit

    Connelly Barnes, Jun 18, 2004, in forum: Python
    Replies:
    0
    Views:
    319
    Connelly Barnes
    Jun 18, 2004
  5. Dan Christensen
    Replies:
    4
    Views:
    599
    Peter Otten
    Jul 14, 2004
Loading...

Share This Page