timing a function with timeit? (newbie problem)

Discussion in 'Python' started by news.west.cox.net, Aug 28, 2003.

  1. Why do I get the exception "global name 'test' is not defined" in this code
    (next to last line) and how do I fix it?

    import timeit
    def test():
    x=2+2
    t = timeit.Timer('test()')
    print t.timeit()
    news.west.cox.net, Aug 28, 2003
    #1
    1. Advertising

  2. news.west.cox.net

    Chad Netzer Guest

    On Wed, 2003-08-27 at 16:45, news.west.cox.net wrote:
    > Why do I get the exception "global name 'test' is not defined" in this code
    > (next to last line) and how do I fix it?
    >
    > import timeit
    > def test():
    > x=2+2
    > t = timeit.Timer('test()')
    > print t.timeit()


    You need to tell it about test() with the setup argument (by either
    defining it directly, or importing it.

    >>> t = timeit.Timer('test()', 'def test(): x = 2+2')
    >>> t.timeit()

    0.61572694778442383

    >>> t = timeit.Timer('test()', 'from __main__ import test')
    >>> t.timeit()

    0.71046602725982666

    This is because globals are at the module scope. The timeit module is
    separate from the interactive (ie. '__main__') namespace. The Timer
    function compiles your code in the namespace where it is defined, not
    where it is called. So, it's 'globals' are the globals in the timeit
    module, and thus, it cannot see your test() function as a global.

    --

    Chad Netzer
    Chad Netzer, Aug 28, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Dan Christensen
    Replies:
    4
    Views:
    566
    Peter Otten
    Jul 14, 2004
  2. flupke
    Replies:
    5
    Views:
    342
    Fredrik Lundh
    May 27, 2005
  3. Steven D'Aprano

    Timing a function object versus timeit

    Steven D'Aprano, Nov 4, 2006, in forum: Python
    Replies:
    2
    Views:
    426
    Steven D'Aprano
    Nov 4, 2006
  4. Dongsheng Ruan
    Replies:
    1
    Views:
    428
    Gabriel Genellina
    Jan 19, 2007
  5. Steven D'Aprano

    Passing function objects to timeit

    Steven D'Aprano, Mar 29, 2008, in forum: Python
    Replies:
    14
    Views:
    1,115
    Peter Otten
    Apr 1, 2008
Loading...

Share This Page