PDA

View Full Version : New forum game: Code Racing.


Sir Penguin
15-09-2003, 06:02:58
All right, I'm taking bets on which piece of Python code will run faster, as measured in a timeit.Timer() class.

Each of these code chunks does the same thing: translates an integer into its corresponding bit string. The question is, which one is more efficient... :hmm:

Pick the faster code, win a prize!*

Code number 1:import math
int_ = 2**32 - 1
bitStr = ""
if int_ == 0:
return "0"
numBits = int(math.log(int_,2))
for i in xrange(numBits,-1,-1):
if int_ & 2**i:
bitStr += '1'
else:
bitStr += '0'
return bitStr
Code number 2:int_ = 2**32 - 1
bitStr = ""
if int_ == 0:
return "0"
while int_ != 0:
if int_ % 2 == 0:
bitStr = '0' + bitStr
else:
bitStr = '1' + bitStr
int_ >>= 1
return bitStrSP

*Prize worth up to US$0.

No longer Trippin
15-09-2003, 06:07:23
The first one

No longer Trippin
15-09-2003, 06:08:04
The second one

No longer Trippin
15-09-2003, 06:08:31
Now where is my prize bitch.

Sir Penguin
15-09-2003, 06:10:36
Bend over.

SP

Deacon
15-09-2003, 17:32:06
I'm gonna guess 1. More complex math, but fewer iterations. Or I don't know what I'm talking about. :)

Spartak
15-09-2003, 18:10:38
:hmm:

Sean
15-09-2003, 18:29:24
I think 2, but is there any reason you use += in 1 and = a + 'string' in the other?

Qaj the Fuzzy Love Worm
15-09-2003, 18:47:14
Originally posted by Sir Penguin
All right, I'm taking bets on which piece of Python code will run faster, as measured in a timeit.Timer() class.

Each of these code chunks does the same thing: translates an integer into its corresponding bit string. The question is, which one is more efficient... :hmm:

1) Does it matter?

2) Do we care?

3) I'd say 2 also, because it seems to have less complex math and a similar number of iterations :)

Sean - he's working at the bit string from different ends. So in one he's building from the Most Significant Bit and in the other, the LeastSB. I think.

Sean
15-09-2003, 18:48:05
Oh, duh :clueless:.

Drekkus
15-09-2003, 19:19:09
Kewl, a game. I say the first cause it has the cool xrange thingy.

King_Ghidra@home
15-09-2003, 21:59:16
Now this is the kind of thread the tech forum was made for!

Sir Penguin
15-09-2003, 22:45:04
The xrange() function is very cool, Drekkus. It returns a special object with a fast iterator, as opposed to the standard list returned by the range() function.

SP