Skip to main content
 首页 » 编程设计

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

2025年05月04日10Free-Thinker

我想使用 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 中对我有用。