jokosan
jokosan

Reputation: 33

Why is the first sqrt algorithm faster than the second?

I was testing some square root algorithms until i noticed that the first method is faster than the second

    @Benchmark
    @Fork(value = 1)
    @BenchmarkMode(Mode.Throughput)
    public void sqrt1() {
        int number = 25 << 10;
        int result = sqrt1(number);
    }

    @Benchmark
    @Fork(value = 1)
    @BenchmarkMode(Mode.Throughput)
    public void sqrt2() {
        int number = 25 << 10;
        int result = sqrt2(number);
    }

    public static int sqrt1(int number) {
        number >>= 10;
        int c = 0x8000;
        int g = 0x8000;

        if (g * g > number) {
            g ^= c;
        }
        c >>= 1;
        if (c == 0) {
            return g << 10;
        }
        g |= c;
        for (int i = 0; i < 15; i++) {
            if (g * g > number) {
                g ^= c;
            }
            c >>= 1;
            if (c == 0) {
                return g << 10;
            }
            g |= c;
        }
        return g << 10;
    }


    public static int sqrt2(int number) {
        number >>= 10;
        int c = 0x8000;
        int g = 0x8000;

        for (int i = 0; i < 16; i++) {
            if (g * g > number) {
                g ^= c;
            }
            c >>= 1;
            if (c == 0) {
                return g << 10;
            }
            g |= c;
        }
        return g << 10;
    }

Benchmark results

Benchmark          Mode  Cnt          Score         Error  Units
Benchmarks.sqrt1  thrpt   20  104918275,263 ± 1080520,157  ops/s
Benchmarks.sqrt2  thrpt   20   93597198,803 ±  417763,363  ops/s

Why is the first method faster than the second?

Benchmarks done using jhm and java 8

-Windows 10 Home

-Intel Core [email protected]

-16GB RAM

Upvotes: 2

Views: 124

Answers (1)

WJS
WJS

Reputation: 40044

The first one only loops 15 times. The second one loops 16 times. So you are doing one less increment and compare in the first one. I would imagine that if you just repeat the computation 16 times without using a loop it would speed up even more. But this is just a hunch.

Upvotes: 2

Related Questions