简体   繁体   English

NameError在python中使用timeit

[英]NameError for using timeit in python

I got NameError when I try to run this codes."global name j is not defined". 尝试运行此代码时出现NameError 。“未定义全局名称j”。 How can I fix it? 我该如何解决?

def test(j):
    for i in range(j):
        j = i**2

if __name__=='__main__':
    from timeit import Timer
    j = 30
    t = Timer("test(j)","from __main__ import test")
    print( t.timeit(j))

Timer doesn't know about j . Timer不知道j You need to do something like "test(%d)" % j (or from __main__ import j or put the definition of j inside the string, too). 你需要做一些像"test(%d)" % j (或from __main__ import j或放的定义j里面的字符串,太)。

Also, the argument to timeit is different from the argument to your test function (so the different uses of j are probably not what you should do or mean). 而且, timeit的参数与test函数的参数不同(因此j的不同用法可能不是您应该做的或不想要的)。 The timeit argument gives the number of executions for the test function. timeit参数给出测试功能的执行次数。

ps Note that you need to indent any code in your question to get it formatted ps注意,您需要缩进问题中的任何代码以将其格式化

pps There used to be a comment here about not using from __main__ import but that actually does work! pps这里曾经有一段评论,关于不使用from __main__ import但这确实有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM