Python 列表:为什么 .sort() 比 sorted() 快得多



我测量对 1000 万个条目的列表进行排序所需的时间:

import time
a = range(10000000, 0, -1)
b = range(10000000, 0, -1)
start = time.time()
a.sort()
end = time.time()
print end - start
start = time.time()
sorted(b)
end = time.time()
print end - start

我得到的输出:

0.272000074387
0.468999862671

原因可能是因为sorted更通用,但这与这篇文章不一致差异在大列表中变得微不足道。是什么导致了巨大的差异?

我在 2.7.3 位 Windows 32、Q6600 处理器上使用 python 2.7.3 32 位。

sort 版本就地对列表进行操作,但sorted创建列表的副本。当实际排序如此简单时(Timsort 检测到整个列表是一个大的向后运行并反转它),副本的创建可能会对运行时产生重大影响。

相关内容

最新更新