I want to time three similar functions with timeit. I have written this code, but I don't understand what's is happening when I am passing a function to the test function.
def f0(x, y, z):
#some code here
def f1(x, y, z):
#a slighty similar function
def f2(x, y, z):
#still another similar function
def test(name):
x=100
y=100
z=100
res=name(x,y,z)
if __name__ == '__main__':
import timeit
print(timeit.timeit("test(f0)", setup="from __main__ import test"))
The error I got is:
NameError: global name 'f0' is not defined
You need to import all global names mentioned in the test:
print(timeit.timeit("test(f0)", setup="from __main__ import test, f0"))
The line test(f0)
needs to look up f0
too, not just test()
.
你也必须导入f0
,就像这样
print(timeit.timeit("test(f0)", setup="from __main__ import test, f0"))
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.