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

Python中`in`运算符计时测试异常结果的原因咨询

Python中in运算符计时测试异常结果的原因咨询

我最近在研究Python里in运算符的内部工作机制,为了搞清楚它的原理,我做了一个计时测试:统计在列表不同位置查找元素所花费的时间。

下面是我用到的测试代码:

import time
import matplotlib.pyplot as plt

# list size
size = 100000
# number of points
n = 100000

# display for not having to count zeros
if size >= 1000000:
    new_size = str(int(size/1000000))+"M"
else:
    new_size = str(int(size/1000))+"K"

if n >= 1000000:
    new_n = str(int(n/10000000))+"M"
elif n >= 1000:
    new_n = str(int(n/1000))+"K"
else:
    new_n = n

lst = list(range(size))
result = []
for number in range(0,size+1,int(size/n)):
    start_time = time.time_ns()
    if number in lst:
        end_time = time.time_ns()
        total_time = (end_time-start_time)/1000000000 #convert ns to seconds
        result.append([total_time,number])
        print(number,total_time)

x_values, y_values = zip(*result)
plt.scatter(x_values, y_values, c='red', marker='o',s=5)
plt.xlabel('Time (sec)')
plt.ylabel('Number')
plt.title(f'List length: {new_size}\nNumber of points: {new_n}\n\nTime to find number in list')
plt.grid(True)
plt.show()

根据我了解的知识,in运算符内部会调用iter方法,按顺序遍历可迭代对象的元素,从第一个开始。所以我原本预期的是:元素在列表中的位置越靠后,查找花费的时间应该越长。

为了能测出明显的时间差异,我特意用了足够长的列表。但调试不同的列表长度和测试点数后,我发现测试结果的点都集中在0.001秒的倍数对应的竖线上,这太奇怪了!我能理解如果出现水平线可能是Python内部机制导致的,但竖线完全不符合预期啊。我甚至用了time.time_ns()来提高时间精度,结果还是一样。

我实在想不通:在[0,1,...,100000]这样的列表里,查找539和94598怎么会花费一样的时间呢?毕竟in是从列表开头开始顺序查找的啊。

附上我的测试结果图:
100,000 points

备注:内容来源于stack exchange,提问作者Kostas V.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 18:00:31