views:

54

answers:

1

Here's a piece of code that takes most time in my program, according to timeit statistics. It's a dirty function to convert floats in [-1.0, 1.0] interval into unsigned integer [0, 2**32]. How can I accelerate floatToInt?

piece = []
rng = range(32)
for i in rng:
    piece.append(1.0/2**i)

def floatToInt(x):
    n = x + 1.0
    res = 0
    for i in rng:
        if n >= piece[i]:
            res += 2**(31-i)
            n -= piece[i]

    return res
+4  A: 

Did you try the obvious one?

def floatToInt(x):
    return int((x+1.0) * (2**31))
Joachim Sauer
No, I made things more complicated. This worked 10x faster.
culebrón
2**31 evaluates to 2147483648 every time. Since you are focused on speed here, replacing 2**31 with this constant is one less calculation you'll need to do in your time-critical code segment.
Paul McGuire
I checked with timeit and 2**31 is only slower when there is no "x" in the equation??
pixelbeat
Import the dis module to disassemble the code for floatToInt using `dis.dis(floatToInt)` to see that Python evaluates this constant internally, so this part of the calculation is *not* done at loop runtime.
Paul McGuire