Die Meldung "global name 'foo' ist nicht definiert" mit Pythons timeit

Ich versuche, herauszufinden, wie viel Zeit es braucht, um führen Sie eine Python-Anweisung, also suchte ich online und fand, dass die standard-Bibliothek bietet ein Modul namens timeit, die vorgibt, genau das zu tun:

import timeit

def foo():
    # ... contains code I want to time ...

def dotime():
    t = timeit.Timer("foo()")
    time = t.timeit(1)
    print "took %fs\n" % (time,)

dotime()

Jedoch, dies produziert einen Fehler:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in dotime
  File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 6, in inner
NameError: global name 'foo' is not defined

Ich bin noch neu in Python und verstehe ich nicht alle der scoping-Probleme hat, aber ich weiß nicht, warum dieses snippet funktioniert nicht. Irgendwelche Gedanken?

InformationsquelleAutor Kyle Cronin | 2009-02-15

Schreibe einen Kommentar