我知道__builtin__
sorted()函數適用於任何迭代。但是有人可以解釋一下anylist.sort()與sorted(anylist)之間的巨大(10倍)性能差異嗎?另外,請指出我是否以這種測量方式做錯了什麼。列表vs內置排序()函數的Python排序()方法
""" Example Output: $ python list_sort_timeit.py Using sort method: 20.0662879944 Using sorted builin method: 259.009809017 """ import random import timeit print 'Using sort method:', x = min(timeit.Timer("test_list1.sort()","import random;test_list1=random.sample(xrange(1000),1000)").repeat()) print x print 'Using sorted builin method:', x = min(timeit.Timer("sorted(test_list2)","import random;test_list2=random.sample(xrange(1000),1000)").repeat()) print x
正如標題所說,我很感興趣,比較list.sort()與排序(列表)。上面的代碼片段顯示了一些有趣的事情,python的排序函數對於已排序的數據表現得非常好。正如Anurag所指出的那樣,在第一種情況下,排序方法正在處理已經排序的數據,而在第二種排序方法中,它正在處理新鮮事物以便一次又一次地工作。
所以我寫了這個測試,是的,他們非常接近。
""" Example Output: $ python list_sort_timeit.py Using sort method: 19.0166599751 Using sorted builin method: 23.203567028 """ import random import timeit print 'Using sort method:', x = min(timeit.Timer("test_list1.sort()","import random;test_list1=random.sample(xrange(1000),1000);test_list1.sort()").repeat()) print x print 'Using sorted builin method:', x = min(timeit.Timer("sorted(test_list2)","import random;test_list2=random.sample(xrange(1000),1000);test_list2.sort()").repeat()) print x
哦,我看到亞歷克斯·馬爾泰利有反應,因爲我打字這一個。(我將離開這個編輯,因爲它可能是有用的)。
順便說一句,因爲這是一個合法答案的問題,它可能不應該是社區wiki。 – 2009-09-17 06:15:28
好的,我會記住的,丹尼爾。這是一個很好的指針。 – 2009-09-17 06:23:36