python timeit模块重复函数

python timeit模块重复函数,python,Python,我有四个函数名为numbers\u string1、numbers\u string2、numbers\u string3、numbers\u string4,我需要找出这些函数的执行时间 from numstring import * import time def profile_clock(): l=["numbers_string1","numbers_string2","numbers_string3","num_strings4"] for i in l:

我有四个函数名为numbers\u string1、numbers\u string2、numbers\u string3、numbers\u string4,我需要找出这些函数的执行时间

from numstring import *
import time
def profile_clock():
    l=["numbers_string1","numbers_string2","numbers_string3","num_strings4"]
    for i in l:
        count=1
        for j in range(5):
            m=[]
            count=count*10
            m=timeit.repeat("i(count)",5,count)
            #m=t.repeat(5,count)
            print i,(),"count=",count,"min=",min(m),"atuals=",m
当我执行此操作时,由于未定义全局名称I,因此出现错误。

timeit函数在其自己的函数空间中运行。它不能访问您的作用域,这就是为什么它提供了一个设置参数,它执行该参数来设置计时环境。您需要在字符串中定义所需的任何函数和变量,然后将其作为设置参数传递给timeit.repeat

你似乎也误解了其他一些事情的工作原理。当你把i放在一个字符串中时,它只是字母i。它不会神奇地接受变量i的值。就这一点而言,两者都不重要。您需要创建一个字符串来保存一些实际值,而不是变量名

在我看来,你想做这样的事情:

setup = 'from numstring import *' # String to execute to set up the timeit scope
funcs = ["numbers_string1", "numbers_string2", "numbers_string3", "num_strings4"]
for func in funcs: # Better variable names are better!
    for count in (1, 10, 100, 1000, 10000): # Clean up this iteration
        statement = '{f}({n})'.format(f=func, n=count) # the call to test
        m = timeit.repeat(statement, setup=setup, repeat=5)
我强烈建议您,因为m=timeit.repeaticount,5,count从一开始就不是该函数的合法使用。

使用timeit的测试在其各自独立的范围内执行。这主要是为了使计时不受执行测试的模块中某些副作用的影响。因此,在测试期间既没有定义i,也没有定义函数编号\u string1/2/3/4

您可以通过设置它们来导入它们,例如:

timeit.repeat("numbers_string1(count)", 5, count, setup='from __main__ import numbers_string1')
但这并不能解决您的问题,因为我仍然没有定义,即使定义了,它也将是一个字符串,而不是您可以执行的函数。你的意图可能是:

timeit.repeat('{}({})'.format(i, count), repeat=5, setup='from __main import ' + i)