从timeit()中的同一模块调用方法时发生导入错误

2024-10-03 13:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

代码如下:

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

def sayHello():
    print("Hello")

我一直收到一个重要的警告:“无法导入文件中的名称sayHello…”

我向Timer构造函数添加了scope参数("from __main__ import sayHello"),使sayHello()方法在timeit范围内可用。在

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

有人能帮忙吗? 谢谢。在


Tags: 模块方法代码fromimporthelloreturnmain
2条回答

我有一个文件是这样的:

import timeit

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

def sayHello():
    print("Hello")

print(getExecutionTime())

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

你在IDE中运行这个吗?从命令行&IDLE,它在python2.7&3.2下都适用。在

代码,正如它所写的,并且导入了timeit,对我来说也很好,不是很重要。。。在

相关问题 更多 >