使用timeit测试内置函数sum()遇NameError错误的问题咨询
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:
Use the
setupparameter to expose your variable
Thesetupargument 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 sline pulls your existingsvariable into thetimeitnamespace so it can be accessed.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))Pass the global namespace directly (Python 3.5+)
You can explicitly tell the Timer to use your current global namespace with theglobalsparameter—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

