gpt4 book ai didi

python - 在 timeit() 中从同一模块调用方法时导入错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:04 26 4
gpt4 key购买 nike

我想使用 getExecutionTime() 方法测量 Python 方法 sayHello() 的执行时间。它们都在一个模块中,getExecutionTime() 方法应该可以从外部调用。

代码如下所示:

def getExecutionTime():
t = timeit.Timer("sayHello", "from __main__ import sayHello")
return t.timeit(2)

def sayHello():
print("Hello")

我不断收到 ImportError 消息:“无法在文件中导入名称 sayHello ...”

我将范围参数(“from __main__ import sayHello”)添加到 Timer 构造函数,以使 sayHello() 方法在 timeit 范围内可用。

注意:我不想在此方法的主要部分调用 getExecutionTime(),我想从其他地方调用该方法。

有人可以帮忙吗?谢谢。

最佳答案

我有一个文件,字面上是这样的:

import timeit

def getExecutionTime():
t = timeit.Timer("sayHello()", "from __main__ import sayHello")
return t.timeit(2)

def sayHello():
print("Hello")

print(getExecutionTime())

运行时,它会打印两次Hello,然后是执行时间。 (另请注意,在 Timer 设置中,它是 sayHello() 而不是 sayHello

您是在 IDE 中运行它吗?在 Python 2.7 和 3.2 下,它在命令行和 IDLE 中对我有用。

关于python - 在 timeit() 中从同一模块调用方法时导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12404487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com