Search code examples
pythonbenchmarking

How to import functions from the interactive session namespace for timeit benchmarks?


I found the following example in Python's document.

def test():
    """Stupid test function"""
    L = []
    for i in range(100):
        L.append(i)

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test()", setup="from __main__ import test"))

However that only works when the code is defined in a script. How can I test a function that is defined in a Python repl? Hope someone can point me the right direction. Below is my testing.

>>> import timeit
>>> dir(timeit)
['Timer', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__sp
ec__', '_globals', 'default_number', 'default_repeat', 'default_timer', 'dummy_src_name', 'gc', 'itertools', 'main', 're
indent', 'repeat', 'sys', 'template', 'time', 'timeit']
>>> help(timeit.timeit)
Help on function timeit in module timeit:

timeit(stmt='pass', setup='pass', timer=<built-in function perf_counter>, number=1000000, globals=None)
    Convenience function to create Timer object and call timeit method.

>>> timeit.timeit('''a=""; a+="b"*1000;''')
0.14870357161726633
>>> timeit.timeit('''a=""; a+="b"*1000;''')
0.13576636550958954
>>>
>>>
>>> def testme():
...     a = ""
...     a = "eyang" * 10000
...
>>> timeit("testme()")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>>
>>> timeit("testme()", setup="from __main__ import testme")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>>

Solution

  • If you're running an interactive console session aka REPL, it is the __main__ module:

    In [228]: def x():print "foo"
    
    In [229]: from __main__ import x
    
    In [230]: x()
    foo
    

    That said, in IPython, there's the timeit magic command that runs the code in the interactive namespace by default, saving you the need to type the set-up code.