如何从 timeit 基准测试的交互式会话命名空间导入函数?

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

我在 Python 的文档中找到了以下示例。

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"))

然而,只有在脚本中定义代码时才有效。如何测试 Python repl 中定义的函数?希望有人能给我指出正确的方向。下面是我的测试。

>>> 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
>>>

如果您是 运行 交互式控制台会话 aka REPL,__main__ 模块:

In [228]: def x():print "foo"

In [229]: from __main__ import x

In [230]: x()
foo

也就是说,在 IPython 中,有 timeit 魔法命令默认运行交互式命名空间中的代码,让您无需键入 set-up 代码。