测试对于list的sort与sorted的效率

sorted

from time import clock
from random import randint
start = clock()
a = [randint(0,1000000) for i in range(1000000)]
# a.sort()
a = sorted(a)
end = clock()
print a
print "time cost is %f s" %((end-start)*10)

结果:
time cost is 35.358285 s*

sort

from time import clock
from random import randint
start = clock()
a = [randint(0,1000000) for i in range(1000000)]
a.sort()
# a = sorted(a)
end = clock()
print a
print "time cost is %f s" %((end-start)*10)

结果:
time cost is 34.877686 s

总结

  • 对于 list 而言,sort() 比 sorted() 效率要高
  • 但是 sorted() 用途更广,可以用于任何可迭代容器;而 sort() 只能用于 list
posted @ 2016-11-23 10:28  岳麓丹枫  阅读(529)  评论(0编辑  收藏  举报