gpt4 book ai didi

Python 列出 : why is . sort() 比 sorted() 快得多?

转载 作者:行者123 更新时间:2023-11-28 21:21:20 25 4
gpt4 key购买 nike

我测量了对包含 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比较通用,但这与this post不一致|在大型列表中差异变得微乎其微。是什么造成了巨大的差异?

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

最佳答案

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

关于Python 列出 : why is . sort() 比 sorted() 快得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21645469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com