2

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

1 Answer 1

5

Did you try the obvious one?

def floatToInt(x):
    return int((x+1.0) * (2**31))
Sign up to request clarification or add additional context in comments.

3 Comments

231 evaluates to 2147483648 every time. Since you are focused on speed here, replacing 231 with this constant is one less calculation you'll need to do in your time-critical code segment.
I checked with timeit and 2**31 is only slower when there is no "x" in the equation??
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.