4

I originally made a custom function for timing functions that looks like this:

def timefunc(function, *args):
    start = time.time()
    data = function(*args)
    end = time.time()
    time_taken = end - start
    print "Function: "+function.__name__
    print "Time taken:",time_taken
    return data

Now, having learned about the timeit module, I want to implement the same thing using that. I just can't figure out how to do it while sending it the function and *args arguments. I have already figured out that I have to do this in the setup arg:

"from __main__ import function"

But I can't figure out what to do about *args, since both the 'stmt' and 'setup' arguments are strings, how can I pass the variables?

talloaktrees
  • 3,508
  • 6
  • 28
  • 43

1 Answers1

6

Starting with Python 2.6 the timeit module besides a string also accepts a callable as stmt. With that in mind you can do this:

import timeit

def timefunc(function, *args):
    def wrap():
        function(*args)
    t = timeit.Timer(wrap)
    return t.timeit(100)

def test(arg):
    foo = arg

print(timefunc(test, 'bar'))
Rob Wouters
  • 15,797
  • 3
  • 42
  • 36