我正在尝试监控 Python 列表中的复杂性。因此,我编写了上面的脚本,认为在末尾插入一个项目的复杂度为 O(1),在开头插入的复杂度为 O(n),如下所示
import time
for p in [3,4,5,6,7]:
n = 10**p
print("n =", n, ":")
# Creation of a list [0, 1, ..., n]
li = list(range(n))
start = time.perf_counter()
# Adding item at the end
li.append('a')
stop = time.perf_counter()
duration = round((stop - start)*1000, 3)
print("Time for insertion at the end :", duration, "ms")
start = time.perf_counter()
# Adding item at the beginning
li.insert(0,'a')
stop = time.perf_counter()
duration = round((stop - start)*1000, 3)
print("Time for insertion at the beginning :", duration, "ms")
print()
结果是:
n = 1000 :
Time for insertion at the end : 0.001 ms
Time for insertion at the beginning : 0.001 ms
n = 10000 :
Time for insertion at the end : 0.003 ms
Time for insertion at the beginning : 0.007 ms
n = 100000 :
Time for insertion at the end : 0.036 ms
Time for insertion at the beginning : 0.098 ms
n = 1000000 :
Time for insertion at the end : 0.05 ms
Time for insertion at the beginning : 1.001 ms
n = 10000000 :
Time for insertion at the end : 0.257 ms
Time for insertion at the beginning : 11.453 ms
因此,开头的插入显然是 O(n),但末尾的插入显然不是 O(1)。
有人可以向我解释一下吗?
配置:Ubuntu 20.04.1 LTS 上的 Python 3.8.5
因此,我尝试使用 timeit (按照建议),结果是应有的结果。
尚方宝剑之说
相关分类