No built-in swap function?

Simon Wittber drconrad at metaplay.com.au
Wed Apr 21 01:49:11 EDT 2004


For interest's sake, I wrote the following test:


import time
def tupleSwap(a,b):a,b = b,a
def tempSwap(a,b):
    t = a
    a = b
    b = t
def xorSwap(a,b):
    a ^= b
    b ^= a
    a ^= b
s = time.clock()
for i in xrange(1000000): tupleSwap(1,2)
t = time.clock() - s
print "1 million tuple swaps in", t, "seconds."
s = time.clock()
for i in xrange(1000000): tempSwap(1,2)
t = time.clock() - s
print "1 million temp swaps in", t, "seconds."
s = time.clock()
for i in xrange(1000000): xorSwap(1,2)
t = time.clock() - s
print "1 million xor swaps in", t, "seconds."


And received the following output:
1 million tuple swaps in 1.78324228359 seconds.
1 million temp swaps in 1.53032270861 seconds.
1 million xor swaps in 2.17933312753 seconds.

Interestingly, using psyco.full() produced these results:
1 million tuple swaps in 3.06005958858 seconds.
1 million temp swaps in 3.01621882111 seconds.
1 million xor swaps in 3.03376686143 seconds.

The xorswap function is not much use for anything other than numbers,
however, I would have expected a psyco'ed xorSwap to much faster than
the alternatives!

Sw.





More information about the Python-list mailing list