计算执行时间时,使用 timeit 时出现“TypeError:'module'不可调用”的错误

2024-05-08 16:25:35 发布

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

我试图计算我的python代码的计时,但我一直得到:

TypeError - 'module' is not callable

import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

我正在检查的链接是-https://docs.python.org/2/library/timeit.html

我希望看到代码运行所花费的时间。在


Tags: 代码inimportnumberforisnotrange
2条回答

你可能把你的文件命名为timeit.py?在

$ cat timeit.py
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
$ python3 timeit.py
Traceback (most recent call last):
  File "timeit.py", line 1, in <module>
    import timeit
  File "/path/to/timeit.py", line 2, in <module>
    timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
TypeError: 'module' object is not callable

您必须将文件重命名为其他文件(例如我的时间信息.py 否则将导入>。在

您可以使用print(timeit.__file__)检查import-ed模块。
如果你还需要时间来打印代码。在

^{pr2}$

我们走!在

import time

origin_time = time.time()这样,您将从epoch获得当前时间(以秒为单位)

无论何时你想知道花了多少时间,只要写下:

current_spent_time = time.time() - origin_time这将再次获得当前时间(以秒为单位),并减去以前的源时间,即代码开始运行的时间。在

希望这有帮助!!在

相关问题 更多 >

    热门问题