如何在使用timeit.Timer()时传递函数参数

75
这是一个简单程序的大纲。
# some pre-defined constants
A = 1
B = 2

# function that does something critical
def foo(num1, num2):
    # do something

# main program.... do something to A and B
for i in range(20):
    # do something to A and B
    # and update A and B during each iteration

import timeit
t = timeit.Timer(stmt="foo(num1,num2)")  
print t.timeit(5)

我一直在收到"global name foo is not defined"的错误提示......谁能帮忙解决一下吗?谢谢!

首先,这里的缩进很令人困惑。看起来 foo 被定义在不同于 t 的作用域中... - senderle
嗨。我修正了缩进。现在看起来更好了吗?:] 谢谢。 - CppLearner
timeit 对于一行代码是可以的,但对于其他情况最好检查这个方法:https://dev59.com/OW035IYBdhLWcg3wVul1 - vincent
在Python3中,这个问题有一个非常简单的解决方案,您只需在timeit调用中添加“globals = globals()”参数即可在全局命名空间中运行表达式:https://dev59.com/lm445IYBdhLWcg3wAFm0#51913199 - RustyToms
简而言之:duration,return_value= timeit.Timer(functools.partial(your_function_name, argument_1, argument_2,argument_3)).timeit(1),其中 your_function_namefoo,如果你编写了一个函数如下:def foo(argument_1, argument_2, argument_3):。同时包括 @Hugh Bothwell 的 timeit.template = """.. 块。return_value 是函数返回的值,例如 argument_1 + argument_2。使用 import timeit, functools。此解决方案由 @Jose Ricardo Bustos M. 提供。 - a.t.
12个回答

0
今天我在 Python 3.7 中尝试使用计时器来传递函数和变量。以下是我的代码:
import re

text = "This         is      a  test of the      emergency broadcast       system"

def regex(text):
    return re.sub(r"(\s)\1{1,}", r"\1", text)

def loop_while(text):
    if "  " in text:
        while "  " in text:
            text = text.replace("  ", " ")

    return text

if __name__ == "__main__":
    import timeit

    callable_functions = [item for item in locals().items() if callable(item[1])]

    for func_name, func in callable_functions:
        elapsed_time = timeit.timeit(f"{func_name}(text)", globals=globals(), number=100000)
        print(f"{func_name}: {elapsed_time} \n{func(text)}\n")

这将输出:

正则表达式:1.378352418
这是紧急广播系统的测试

循环_while:0.15858950299999997
这是紧急广播系统的测试

然后,要测试新版本,只需添加一个新函数即可。例如:

def split_join(text):
    return " ".join(text.split())

现在输出的结果为:

正则表达式: 1.378352418
这是紧急广播系统的测试

while循环:0.15858950299999997
这是紧急广播系统的测试

字符串分割和连接:0.05700970800000005
这是紧急广播系统的测试


0

你必须在设置字符串内创建变量。这里我导入函数,并创建其中一个变量,然后将其传递给函数。我还通过将其转换为stmt字符串来设置其中一个变量。

SETUP = '''
from __main__ import policy_iteration
from environments.gridworld import GridworldEnv

env = GridworldEnv()
'''

discount = 5
timeit.timeit("policy_iteration(env,discount_factor="+str(discount)+")",
                          setup= SETUP,
                          number=10))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接