2

I have a Python function called func that I am trying to time using timeit.

func takes an argument, f, that is also a function. In the program I'm writing, it's a lambda function, but it can be a regularly defined function as well. What matters is that the source code for this function is not available to func, all that's available is a reference to it.

What I'm trying to do:

def testTimingOfFunc(f):
    time = timeit.timeit("package.func(f)", "from src import package")

I get an error that says that f isn't defined.

Everything else is working correctly. When I call:

testTimingOfFunc('lambda x:x**2')

and change the function to:

def testTimingOfFunc(f):
    time = timeit.timeit("package.func(" + str(f) + ")",
                         "from src import package")

everything works as it should, so I know that everything regarding the timeit function is fine.

That's not how testTimingOfFunc works though; A function reference gets passed in, not a string.

Any ideas on how I can pass f as an argument to func in timeit?

3 Answers 3

5

timeit can be called with a python callable value: just change your method to:

from src import package
import functools

def testTimingOfFunc(f):
    time = timeit.timeit(functools.partial(package.func, f))
Sign up to request clarification or add additional context in comments.

Comments

1

You could store a reference to f in the namespace of package. Be careful that you don't have name conflicts though

def testTimingOfFunc(f):
    from src import package
    package.f = f
    time = timeit.timeit("package.func(package.f)", "from src import package")

Comments

0

timeit.Timer accepts a no-argument function as one of its parameters:

def tester(f):
    from src import package
    def wrapper():
        package.func(f)
    return wrapper

def foo(x):
    return x * 2

print(timeit.timeit(tester(foo)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.