No built-in swap function?

Josiah Carlson jcarlson at uci.edu
Wed Apr 21 11:36:01 EDT 2004


>>> 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!
>>
>>
>>
>> You are testing function calling overhead.  Try the below...
>>
>> import time
>>
>> def tupleswap(a,b):
>>     t = time.time()
>>     for i in xrange(100000):
>>         a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;
>>         a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;a,b=b,a;
>>     print "1 million tuple swaps in", time.time()-t, "seconds."
> 
> 
> AFAIK, this seems to be 10 thousand instead of 1 million (and 10 mil 
> instead of 100 mil for
> the psyco test).

You need to check your eyes.  In tupleswap, the xrange is 100,000, and 
the body of the for loop contains 10 tuple swaps, where 'a,b=b,a;' is 
one tuple swap.

Similarly for tempswap, the xrange is 100,000, and the body of the for 
loop contains 10 'swaps using a temporary variable', where 
't=a;a=b;b=a;' is considered a single 'swap' of the a and b values, 
using 't' as a temporary value.

This is also equivalent to the xor swap, where 'a^=b;b^=a;a^=b;' is a 
single xor swap, 10 in the body, etc.


It should be trivial (by simple multiplication) that each conceptual 
swap is done 1 million times.  For the big psyco test, I used a bigger 
xrange (100 times bigger in fact), which puts it at 100 million.

Again, check your eyes.

  - Josiah



More information about the Python-list mailing list