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

来源:互联网 发布:java汽车按揭 编辑:程序博客网 时间:2024/06/06 04:19

sorted

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

结果:
time cost is 35.358285 s*

sort

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

结果:
time cost is 34.877686 s

总结

  • 对于 list 而言,sort() 比 sorted() 效率要高
  • 但是 sorted() 用途更广,可以用于任何可迭代容器;而 sort() 只能用于 list
0 0