gpt4 book ai didi

python - Timeit, NameError : global name is not defined. 但我没有使用全局变量

转载 作者:太空狗 更新时间:2023-10-29 20:39:02 26 4
gpt4 key购买 nike

我想测量以下代码的执行速度:

def pe1():
l = []
for i in range(1000):
if i%3 == 0 or i%5 == 0:
l.append(i)
print sum(l)

我将此代码存储在 pe1m.py 下。现在我想用 python 解释器测试文件的速度。我做了:

import timeit
import pe1m

t = timeit.Timer(stmt = 'pe1m.pe1()')
t.timeit()

但我得到:

File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/timeit.py", line 195, in timeit
timing = self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
NameError: global name 'pe1m' is not defined

但是我没有任何全局变量。

最佳答案

试试这个:

t = timeit.Timer(stmt='pe1()', setup='from pe1m import pe1')

timeit.Timer 对象不知道您在其中调用它的命名空间,因此它无法访问您导入的 pe1m 模块。

setup 参数是在定时语句的上下文中执行的语句,它们共享相同的命名空间,因此无论您在那里定义什么,都可以在 stmt 中访问。

关于python - Timeit, NameError : global name is not defined. 但我没有使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com