AttributeError: 'module' object has no attribute 'timeit' while doing timeit a python function

AttributeError: 'module' object has no attribute 'timeit' while doing timeit a python function

我想为 python 函数计时,或者想打印执行 my_function() 12 次迭代所需的最佳时间。 下面是我的代码:

def my_function():
    print "hello"

if __name__ == "__main__":
    import timeit
    setup = "from __main__ import my_function"
    print timeit.timeit("my_function()", setup=setup,number=12)

但我低于错误

Traceback (most recent call last):
  File "timeit.py", line 7, in <module>
    print timeit.timeit("my_function()", setup=setup,number=12)
AttributeError: 'module' object has no attribute 'timeit'

任何人请帮助..

您将文件命名为 timeit.py,它阻止了内置模块,因此 import timeit 正在导入您自己的文件。将您的文件命名为其他名称。