繁体   English   中英

Python:使用timeit的“ from module”与“ from__main__”怪异行为

[英]Python: 'from module' vs. 'from__main__' weird behavior using timeit

我正在学习python,当我意识到无法解释的怪异行为时,我只是在玩timeit模块。

#test.py

import timeit

def dictComp(I):
    return {x: x for x in I}

t = timeit.timeit(number=5,
                  stmt='dictComp(I)',
                  setup='from test import dictComp\nI=range(1000000)')
print(t)

因此,我试图通过调用用户定义的函数来以字典理解的时间来安排字典的创建。 但是,当我使用上面的代码执行此操作时,timeit似乎执行了两次。 解释器输出两个不同的时间。

但是,当我将设置字符串更改为from __main__而不是from test ,timeit只运行一次(如预期的那样)。

那么这两个语句之间有区别吗? 当模块是主模块时, from [module] import [obj]写入是否错误? 还是与timeit的setup参数的工作方式有关?

请赐教。 干杯。

__main__模块不是test模块,即使它们来自同一文件。 当执行命中

from test import dictComp

test.py再次作为test模块而不是main模块执行。 (当执行第二次到达该行时,已经导入了test ,因此该文件不会第三次运行。)

最好将timeit调用之类的内容放在if __name__ == '__main__'卫队中:

if __name__ == '__main__':
    t = timeit.timeit(...)

    print(t)

如果不这样做,那么一定from __main__导入from __main__而不from test导入。

因为您将两次包含test.py文件作为__main__ ,一次包含了test请检查一下!

#test.py

import timeit

def dictComp(I):
    return {x: x for x in I}

print __name__
t = timeit.timeit(number=5,
                  stmt='dictComp(I)',
                  setup='from test import dictComp\nI=range(1000000)')
print(t)

暂无
暂无

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

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