I'm learning python and I was just playing around with the timeit module when I realize a weird behavior I couldn't explain.
#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)
So I'm trying to time the creation of dictionaries with a dict comprehension, by calling a user-defined function. But when I do that with the code above, timeit seems to execute twice. The interpreter output two different times.
But when I change the setup string to be from __main__
instead of from test
, timeit runs only once (as expected).
So is there a difference between the two statements?
Is it wrong to write from [module] import [obj]
when the module is the main module?
or does it have something to do with how the setup parameter of timeit works?
Please enlighten me. Cheers.