Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to import when using timeit?

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.

like image 856
zachwill Avatar asked Jan 07 '11 21:01

zachwill


1 Answers

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.

like image 128
Amber Avatar answered Sep 26 '22 03:09

Amber