[英]Python timeit - TypeError: 'module' object is not callable
I usually use timeit in jupyter notebook like this:我通常在 jupyter notebook 中使用 timeit,如下所示:
def some_function():
for x in range(1000):
return x
timeit(some_func())
and get the result like this:得到这样的结果:
6.3 ms ± 42.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
but today I got an error like this:但是今天我遇到了这样的错误:
TypeError Traceback (most recent call last)
<ipython-input-11-fef6a46355f1> in <module>
----> 1 timeit(some_func())
TypeError: 'module' object is not callable
How does it occur?它是如何发生的?
You are currently trying to execute the timeit
module, rather than the function contained within.您当前正在尝试执行
timeit
模块,而不是其中包含的函数。
You should change your import statement from import timeit
to from timeit import timeit
.您应该将导入语句从
import timeit
更改为from timeit import timeit
。 Alternatively, you can call the function using timeit.timeit
.或者,您可以使用
timeit.timeit
调用该函数。
After searching and trying for a while I realize that when we want to use timeit(some_function())
, we do not need import timeit
but we should write it in another input of jupyter notebook like this:搜索并尝试了一段时间后,我意识到当我们想要使用
timeit(some_function())
,我们不需要import timeit
但我们应该将它写在 jupyter notebook 的另一个输入中,如下所示:
IN [1]:在 [1]:
def some_function():
for x in range(1000):
return x
IN [2]:在 [2]:
timeit(some_func())
and we will get output like this:我们会得到这样的输出:
280 ns ± 2.78 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
When we write it in one input like this:当我们像这样在一个输入中编写它时:
IN [1]:在 [1]:
def some_function():
for x in range(1000):
return x
timeit(some_func())
we'll get an error timeit not define and when we 'import timeit' we'll got another error like I produce on the question TypeError: 'module' object is not callable
.我们会得到一个错误 timeit 未定义,当我们“导入 timeit”时,我们会得到另一个错误,就像我在问题
TypeError: 'module' object is not callable
。
because when we import timeit
we need to specify the stmt and setup (if available) eg:因为当我们
import timeit
我们需要指定 stmt 和设置(如果可用),例如:
import timeit
SETUP = """
import yourmodul_here
"""
TEST_CODE = """
def some_function():
for x in range(1000):
return x
"""
timeit.timeit(stmt=TEST_CODE, setup=SETUP, number=2000000)
And we'll get the output like this:我们会得到这样的输出:
0.12415042300017376
TEST_CODE
run TEST_CODE
运行之前加载的东西 so when we import timeit we need to write more I guess.所以当我们导入 timeit 时,我想我们需要写更多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.