11

I'd 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 stored this code under pe1m.py . Now I'd like to test the speed of file with the 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 don't have any global variables.

Lesmana
  • 25,663
  • 9
  • 82
  • 87
Bentley4
  • 10,678
  • 25
  • 83
  • 134
  • When you are importing the modules, there's a statement: import pe1m which, imho, is a typo for some other module. – hjpotter92 Apr 12 '12 at 22:15
  • Possible duplicate of [Getting "global name 'foo' is not defined" with Python's timeit](https://stackoverflow.com/questions/551797/getting-global-name-foo-is-not-defined-with-pythons-timeit) – sds Sep 20 '17 at 16:21

2 Answers2

17

Try this:

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

timeit.Timer object doesn't know about the namespace you're calling it in so it can't access the pe1m module that you imported.

The setup argument is a statement executed in the context of the timed statement, they share the same namespace so whatever you define there, will be accessible in stmt.

yak
  • 8,851
  • 2
  • 29
  • 23
  • Yes. You need a `setup` to import the module into the time namespace -- whether you use `from` or `pe1m.` is a matter or preference. – agf Apr 12 '12 at 22:39
  • 1
    When I do `t = timeit.Timer(stmt='pe1()', setup='from pe1m import pe1')` then `t.timeit()` it just keeps on printing the output of `pe1m.pe1()`(which is 233168) infinitely. – Bentley4 Apr 14 '12 at 16:32
  • @yak if you update your solution (add the `t.timeit(number=1)` line), I can delete my answer below. – Jakob Kroeker Jul 19 '13 at 23:09
7

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