No built-in swap function?
Josiah Carlson
jcarlson at uci.edu
Wed Apr 21 02:59:59 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."
def tempswap(a,b):
s = time.time()
for i in xrange(100000):
t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;
t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;t=a;a=b;b=a;
print "1 million temp swaps in", time.time()-s, "seconds."
def xorswap(a,b):
t = time.time()
for i in xrange(100000):
a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;
a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;
a^=b;b^=a;a^=b;a^=b;b^=a;a^=b;
print "1 million xor swaps in", time.time()-t, "seconds."
a = 2**30-1
b = 2**16-1
tupleswap(a,b)
tempswap(a,b)
xorswap(a,b)
Without Psyco (on a celeron 400):
1 million tuple swaps in 1.10899996758 seconds.
1 million temp swaps in 0.703000068665 seconds.
1 million xor swaps in 2.14099979401 seconds.
With Psyco (on a celeron 400):
1 million tuple swaps in 0.0 seconds.
1 million temp swaps in 0.0 seconds.
1 million xor swaps in 0.0 seconds.
Having 100 times as many loops for the Psyco run (xrange(10000000))...
1 million tuple swaps in 0.125 seconds.
1 million temp swaps in 0.125 seconds.
1 million xor swaps in 1.04699993134 seconds.
Looks like a big win for Psyco to me.
- Josiah
More information about the Python-list
mailing list