Timeit, NameError: global name undefined. But I did not use a global variable

I would like to measure the execution speed of the following code:

def pe1(): l = [] for i in range(1000): if i%3 == 0 or i%5 == 0: l.append(i) print sum(l) 

I saved this code under pe1m.py. Now I want to check file speed using python interpreter. I did:

 import timeit import pe1m t = timeit.Timer(stmt = 'pe1m.pe1()') t.timeit() 

but I get:

 File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/timeit.py", line 195, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 6, in inner NameError: global name 'pe1m' is not defined 

But I do not have global variables.

+7
source share
2 answers

Try the following:

 t = timeit.Timer(stmt='pe1()', setup='from pe1m import pe1') 
An object

timeit.Timer does not know about the namespace that you are calling it to, so it cannot access the pe1m module that you imported.

The setup argument is an operator executed in the context of the timed command, they use the same namespace, so anything you define there will be available in stmt .

+13
source

You can also try this.

 >>>def pe1(): >>> l = [] >>> for i in range(1000): >>> if i%3 == 0 or i%5 == 0: >>> l.append(i) >>> print(sum(l)) >>> >>>from timeit import time it >>>timeit('pe1()',setup="from __main__ import pe1",number=100) # Run 100 times >>>timeit('pe1()',setup="from __main__ import pe1") # run default times of 1000000 
+2
source

All Articles