JP van Oosten

More on list.sort

Jun 16, 2008

As mentioned in the previous post, I found a new way to call list.sort in python. I did some research with the timeit-module and these were my findings.

Using the cmp-method, the timeit module returned 0.008760 sec/pass, while using the key-method gave me 0.001954 sec/pass. Wow, what a difference!

Here is the code I used:

import timeit
import random

class A(object):
    def __init__(self, data):
        self.data = data
    def __repr__(self):
        return "A(%d)" % self.data

l = [A(x) for x in xrange(1000)]
def get_random_list():
    global l
    random.shuffle(l)
    return l

s = """import operator; get_random_list().sort(lambda a,b: cmp(a.data, b.data))"""
t = timeit.Timer(stmt=s, setup="from __main__ import get_random_list")
s2 = """import operator; get_random_list().sort(key=operator.attrgetter('data'))"""
t2 = timeit.Timer(stmt=s2, setup="from __main__ import get_random_list")

ntries = 10000
print "cmp-method: %f sec/pass" % (t.timeit(number=ntries)/ntries)
print "key-method: %f sec/pass" % (t2.timeit(number=ntries)/ntries)