为什么要使用Python的"sorted()"?比"copy,then .sort()"慢 [英] Why is Python's "sorted()" slower than "copy, then .sort()"

查看:113
本文介绍了为什么要使用Python的"sorted()"?比"copy,then .sort()"慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我运行的代码:

import timeit

print timeit.Timer('''a = sorted(x)''', '''x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]''').timeit(number = 1000)
print timeit.Timer('''a=x[:];a.sort()''', '''x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]''').timeit(number = 1000)

结果如下:

0.00259663215837
0.00207390190177

我想知道为什么使用.sort()总是比sorted()更快,即使两者都在复制列表吗?

注意:我正在带有Win7的2.53Ghz i5上运行Python 2.7

Note: I am running Python 2.7 on an 2.53Ghz i5 with Win7

推荐答案

您所看到的区别很小,对于更长的列表完全消失了.只需将* 1000添加到x的定义中,即可在我的计算机上获得以下结果:

The difference you are looking at is miniscule, and completely goes away for longer lists. Simply adding * 1000 to the definition of x gives the following results on my machine:

2.74775004387
2.7489669323

对于sorted()稍慢一些的原因,我的最佳猜测是sorted()需要使用一些通用代码,这些代码可以将 any 迭代地复制到列表中,同时直接复制列表可以假设来源也是一个列表. CPython使用的排序代码对于list.sort()sorted()实际上是相同的,所以不是造成差异的原因.

My best guess for the reason that sorted() was slightly slower for you is that sorted() needs to use some generic code that can copy any iterable to a list, while copying the list directly can make the assumption that the source is also a list. The sorting code used by CPython is actually the same for list.sort() and sorted(), so that's not what is causing the difference.

编辑:源代码当前开发版本的sorted() 的道德等同于

Edit: The source code of the current development version of sorted() does the moral equivalent of

a = list(x)
a.sort()

实际上,使用此代码而不是第二版可以消除任何列表大小的明显速度差异.

and indeed, using this code instead of your second version eliminates any significant speed differences for any list sizes.

这篇关于为什么要使用Python的"sorted()"?比"copy,then .sort()"慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆