1

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.

4

2 回答 2

2

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

from test import dictComp

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

将诸如您的timeit呼叫之类的东西放在if __name__ == '__main__'警卫中是一种很好的做法:

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

    print(t)

如果你不这样做,那么肯定是 importfrom __main__而不是from test.

于 2014-03-14T00:22:40.647 回答
0

因为您将 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)
于 2014-03-14T00:25:30.843 回答