使用 timeit 时正确的导入方式?
我正在测试我之前的一个问题(将列表变成字典)中的以下代码:
single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
if __name__ == '__main__':
from timeit import Timer
print Timer("dict(zip(single[::2], single[1::2]))",
"from __main__ import single").timeit()
print Timer("si = iter(single); dict(izip(si, si))",
"from __main__ import single; from itertools import izip").timeit()
我不确定使用 timeit
时的最佳实践是否是在 Timer
的语句或设置中导入 izip
(我假设设置,但最终的计时结果会根据我的操作而有所不同)。
无论如何,我只是希望在对代码进行计时等时能从你们那里得到任何额外的见解。(另外,我只是想学习 - 我不会因为过早优化或其他任何事情而遭受痛苦。)
谢谢。
I was testing the following code from one of my previous questions (turning a list into a dictionary):
single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
if __name__ == '__main__':
from timeit import Timer
print Timer("dict(zip(single[::2], single[1::2]))",
"from __main__ import single").timeit()
print Timer("si = iter(single); dict(izip(si, si))",
"from __main__ import single; from itertools import izip").timeit()
And I'm unsure whether best practice when using timeit
is to import izip
in Timer
's statement or setup (I'm assuming setup, but the end timing result differs depending on which I do).
Anyways, I was just hoping for any additional insights from you guys when timing your code, etc. (Also, I'm just trying to learn—I'm not suffering for premature optimization or anything.)
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在设置中进行。毕竟,您不会在每次创建字典时都重新导入模块——整个程序只需要一次。您不关心导入模块的时间。
Do it in setup. After all, you wouldn't be re-importing the module every time you create a dict - only once for the entire program. You don't care about the timing on importing the module.