Getting “global name 'foo' is not defined” with Python's timeit

后端 未结 5 2012
臣服心动
臣服心动 2020-11-28 21:49

I\'m trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called timeit that pur

相关标签:
5条回答
  • 2020-11-28 22:34

    You can try this hack:

    import timeit
    
    def foo():
        print 'bar'
    
    def dotime():
        t = timeit.Timer("foo()")
        time = t.timeit(1)
        print "took %fs\n" % (time,)
    
    import __builtin__
    __builtin__.__dict__.update(locals())
    
    dotime()
    
    0 讨论(0)
  • 2020-11-28 22:35

    With Python 3, you can use globals=globals()

    t = timeit.Timer("foo()", globals=globals())
    

    From the documentation:

    Another option is to pass globals() to the globals parameter, which will cause the code to be executed within your current global namespace. This can be more convenient than individually specifying imports

    0 讨论(0)
  • 2020-11-28 22:44

    add into your setup "import thisfile; "

    then when you call the setup function myfunc() use "thisfile.myfunc()"

    eg "thisfile.py"

    def myfunc():
    
     return 5
    
    def testable(par):
    
     pass
    
    
    
    t=timeit.timeit(stmt="testable(v)",setup="import thisfile; v=thisfile.myfunc();").repeat(10)
    
    print( t )
    
    0 讨论(0)
  • 2020-11-28 22:47

    Change this line:

    t = timeit.Timer("foo()")
    

    To this:

    t = timeit.Timer("foo()", "from __main__ import foo")
    

    Check out the link you provided at the very bottom.

    To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement:

    I just tested it on my machine and it worked with the changes.

    0 讨论(0)
  • 2020-11-28 22:47
    t = timeit.Timer("foo()", "from __main__ import foo")
    

    Since timeit doesn't have your stuff in scope.

    0 讨论(0)
提交回复
热议问题