简体   繁体   中英

Passing a lambda function as a variable to another function in timeit

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 ?

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))

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")

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM