tags:

views:

55

answers:

2

On my single core 1.4 GHz computer, I ran the following 2 timeit codes:

suzan:~$ python -mtimeit "
def count(n):
    while n > 0:
        n -= 1
count(10000000)
"
10 loops, best of 3: 1.73 sec per loop
suzan:~$
suzan:~$ python -mtimeit "
import os       
def count(n):
    while n > 0:
        n -= 1
count(10000000)
"
10 loops, best of 3: 1.18 sec per loop
suzan:~$ 

The second timeit command show lesser time than the first one, even when it contains one extra line of code "import os". Is this unusual behavior or the expected one ?

Any help is greatly appreciated.

+1  A: 

I get effectively (to within 0.4%) the same time with both snippets. Python imports the os module as part of the normal import

>>> import sys
>>> "os" in sys.modules
True
>>> 

so the second bit of code, with the "import os", isn't even hitting the disk. All it does is a check against sys.modules.

You could check if import builtins gives the same reaction, but I'm really at a loss to explain what you see. You can enable the "-v" option(s) when starting Python to get a bit more diagnostics about what it's doing, and compare the results. They should be identical.

Andrew Dalke
+1  A: 

The only possible reason I can think of that could explain such a behaviour, shouldn't really matter: L1 cache line misses, and I am referring to data cache (Python VM bytecodes are not executable code for your processor). The code of your count function is stored as a separate code object, and its start address or its speed shouldn't be affected by the setup code. This is very irregular behaviour.

What's your processor make? Your Python version? Your OS version? And are the test results repeatable?

ΤΖΩΤΖΙΟΥ
cat /proc/cpuinfo: processor:0; vendor_id:GenuineIntel; cpu famiy:6; model:23; model name:Intel(R) Core(TM)2 Solo CPU U3500 @ 1.40GHz; stepping:10; cpu MHz:800.000; cache size:3072 KB; fdiv_bug:no; hlt_bug:no; f00f_bug:no; coma_bug:no; fpu:yes; fpu_exception:yes; cpuid level:13; wp:yes; bogomips:2793.31; clflush size:64; cache_alignment:64; address sizes:36 bits physical, 48 bits virtual; Python Version is 2.6.4; OS version is Ubuntu 9.04; And yes, test results are repeatable.
suzanshakya
@suzan: repeatable even when you reverse the order of the tests? I mean, if you run first the test with "import os" and then the one without "import os"?
ΤΖΩΤΖΙΟΥ
Yes, I've run them many times in any order. Always, the time with "import os" takes lesser time than that without "import os".
suzanshakya