Sorting: too different times. Why?

n00m n00m at narod.ru
Sun Nov 22 07:45:54 EST 2009


> Do you get the same magnitude difference
> if you make Vector a new-style class?

Yes (I mean "No"): new-style's much faster

And now it's elephants instead of vectors.
Def: an elephant is smarter than another one IIF
its size is strictly less but its IQ is strictly
greater

I.e. you can't compare (2, 8) to (20, 50)
or let count them as equally smart elephants.
================================================

class Elephant(object):
    def __init__(self, size, iq):
        self.size = size
        self.iq = iq
    def __cmp__(self, e):
        if self.size < e.size and self.iq > e.iq:
            return -1
        if self.size > e.size and self.iq < e.iq:
            return 1
        return 0

def e_cmp(e1, e2):
    if e1.size < e2.size and e1.iq > e2.iq:
        return -1
    if e1.size > e2.size and e1.iq < e2.iq:
        return 1
    return 0

from random import randint
from time import time

a = []
for i in xrange(200000):
    a.append(Elephant(randint(1, 50000), randint(1, 50000)))
b = a[:]
c = a[:]

print 'Sorting...'

t = time()
b.sort(cmp=e_cmp)
print time() - t

t = time()
c.sort()
print time() - t

print b == c



>>> ===================================== RESTART =====
>>>
Sorting...
1.56299996376
1.95300006866
True



More information about the Python-list mailing list