[Python-Dev] Python3 regret about deleting list.sort(cmp=...)

Steven D'Aprano steve at pearwood.info
Sun Mar 13 02:28:25 CET 2011


Fredrik Johansson wrote:

> Consider sorting a list of pairs representing fractions. This can be
> done easily in Python 2.x with the comparison function lambda
> (p,q),(r,s): cmp(p*s, q*r). In Python 2.6, this is about 40 times
> faster than using fractions.Fraction as a key function.


[steve at sylar ~]$ python2.7 -m timeit -s "L = [(1,2), (3,4), (0,5), 
(9,100), (3,7), (2,8)]" "sorted(L, lambda (p,q),(r,s): cmp(p*s, q*r))"
10000 loops, best of 3: 25.1 usec per loop

[steve at sylar ~]$ python2.7 -m timeit -s "L = [(1,2), (3,4), (0,5), 
(9,100), (3,7), (2,8)]" -s "from fractions import Fraction" "sorted(L, 
key=lambda t: Fraction(*t))"
1000 loops, best of 3: 236 usec per loop


So for a short list, I get a factor of ten difference. For a longer 
list, I'd expect the key function to win out. Much to my astonishment, 
it doesn't -- I get similar results regardless of the size of L.

Size of L   key/cmp
==========  =========
6           9.4
600         13.9
60000       7.0
6000000     6.7




-- 
Steven



More information about the Python-Dev mailing list