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

使用timeit测试内置函数sum()遇NameError错误的问题咨询

Why You're Getting a NameError with timeit and How to Fix It

The Root Cause

Ah, I’ve run into this exact quirk before! Here’s the thing: when you create a timeit.Timer with just the code string "sum(s)", that code runs in a separate, isolated namespace—not the same interactive session where you defined your list s. Even though s works fine when you call it directly, timeit doesn’t automatically inherit variables from your current environment by default. That’s why it throws a NameError like it has no idea what s is.

Fixes to Try

Here are a few straightforward, practical ways to fix this:

  1. Use the setup parameter to expose your variable
    The setup argument lets you run code that sets up the environment before the timed code executes. This is the cleanest approach if you want to keep variable setup separate from the code you’re timing:

    s = [1,2,3]
    t = timeit.Timer("sum(s)", setup="from __main__ import s")
    print(t.timeit(5))
    

    The from __main__ import s line pulls your existing s variable into the timeit namespace so it can be accessed.

  2. Include variable setup in the timed code string
    If you don’t mind including the list creation in your timing (note: this will add the time of making the list to your measurement, so only do this if that’s intentional):

    t = timeit.Timer("s = [1,2,3]; sum(s)")
    print(t.timeit(5))
    
  3. Pass the global namespace directly (Python 3.5+)
    You can explicitly tell the Timer to use your current global namespace with the globals parameter—this is super convenient for interactive sessions:

    s = [1,2,3]
    t = timeit.Timer("sum(s)", globals=globals())
    print(t.timeit(5))
    

Quick Check

After trying any of these, you should see the execution time printed without the NameError—the timeit function will now recognize your s variable and measure sum(s) correctly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:05:22