Question

When working with IEEE754 floats I've found two ways of zeroing top 9 bits of a 32bit variable. Is any of them better than the other?

Java related addition: is there some list providing information about instruction efficiency? I've randomly found out that BIPUSH is generally supposed to be faster than LDC but not much anything else.

// 10111111110010100011110101110001 bits
// 00000000010010100011110101110001 significand

int bits = 0b10111111110010100011110101110001;
int significand = bits & 0b11111111111111111111111;
int significand2 = bits << 9 >>> 9;

Bytecode…

L4
    LINENUMBER 49 L4
    ILOAD 0
    LDC 8388607 // = 0b11111111111111111111111
    IAND
    ISTORE 5
L5
    LINENUMBER 50 L5
    ILOAD 0
    BIPUSH 9
    ISHL
    BIPUSH 9
    IUSHR
    ISTORE 6

Thanks. :)

Was it helpful?

Solution

Bytecode is a portable intermediate language. To get decent performance modern JVMs compile it to native code just-in-time, so don't read too much into it: what the CPU will actually execute may look very different. You would have to analyze the generated native code to be able to draw conclusions on why X performs better than Y.

How to get a print-out of the generated assembler code depends on the JVM, see here for instructions for Hotspot (i.e. Oracle JDK and OpenJDK): http://mechanical-sympathy.blogspot.com/2013/06/printing-generated-assembly-code-from.html

OTHER TIPS

In general, shift operation should be faster. Here's a simple Java test and result values:

int bits = 0b10111111110010100011110101110001;

long time = System.nanoTime();
int significand;
for (int i = 0; i < 1000000000; i++) {
    significand = bits & 0b11111111111111111111111;
}
System.out.println(String.format("Time: %f (ms)",
    (System.nanoTime() - time) / 1000000f));

long time2 = System.nanoTime();
for (int i = 0; i < 1000000000; i++) {
    significand = bits << 9 >>> 9;
}
System.out.println(String.format("Time 2: %f (ms)",
    (System.nanoTime() - time2) / 1000000f));

Time 1: 7.003190 (ms)
Time 2: 2.633435 (ms)

These are, of course, results for enormous number of repetitions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top