You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

Testing REPL-Defined Functions with timeit

Got it, I've run into this exact issue before—when you're tinkering in the REPL and want to benchmark a function you just defined, the standard timeit examples (which assume script-level code) don't work out of the box. Here are a few straightforward ways to make this work:

1. Pass the Current REPL Namespace to timeit

The simplest approach is to use timeit.timeit() directly in the REPL, and tell it to use your current global namespace so it can find the function you defined.

First, define your function in the REPL:

def my_repl_func():
    total = 0
    for i in range(10000):
        total += i * 2
    return total

Then run the benchmark with the globals parameter set to globals():

import timeit
timeit.timeit('my_repl_func()', globals=globals(), number=1000)

The globals=globals() argument tells timeit to execute the test code in your current REPL's namespace, so it can resolve references to my_repl_func without any issues.

2. Embed the Function Definition in the Timeit String

If you want to keep the benchmark self-contained (or avoid relying on the current namespace), you can include the function definition directly in the string you pass to timeit:

import timeit
timeit.timeit('''
def my_repl_func():
    total = 0
    for i in range(10000):
        total += i * 2
    return total
my_repl_func()
''', number=1000)

Note that this will redefine the function every time the test runs, which adds a tiny bit of overhead. For most benchmarks, this is negligible, but if you're testing extremely fast functions, keep this in mind.

3. Use IPython's Magic Commands (If You're Using IPython)

If you're using IPython instead of the standard Python REPL, you can skip the boilerplate entirely with the %timeit magic command. Just define your function as usual, then run:

%timeit my_repl_func()

IPython handles the namespace automatically, so this is by far the most convenient option if you're already using it.

Why the Official Script Examples Don't Work in the REPL

The official timeit examples often use strings that reference functions defined in the same script. In the REPL, timeit runs its code in a separate, clean namespace by default—so it can't see the functions you've defined in your current REPL session unless you explicitly pass the namespace via globals=globals().

内容的提问来源于stack exchange,提问作者user130268

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:07:25