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']开发者_StackOverflow
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.
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.
精彩评论