Vector3f.divide() - is multiplication more efficient than division?

In Vector3f.divide() and Vector3f.divideLocal() the argument is first inverted 1/arg and then each component of the vector is multiplied by the inverted value.

Is float multiplication more efficient than float division?



    public Vector3f divideLocal(float scalar) {
        scalar = 1f/scalar;
        x *= scalar;
        y *= scalar;
        z *= scalar;
        return this;
    }

Yes. On the Pentium III, it used to be 3 cycles latency for a multiply (and it could pipeline) versus 14 cycles for a divide (and it couldn't pipeline). I can only imaging it's not gotten better.

Thanx for the info, jwatte!

In case anyone wants to try it out.

The 1/scalar version is indeed a tiny little bit faster. But its almost unnoticeable.

Its about 6 ms, with 1'000'000 iterations :slight_smile:



If you use the following code, one for loop must be commented out!

If both versions run, the second for loop will always be faster. It seems like the JVM is optimizing something in the 2nd run somehow.

But if you run them separately, you'll see that the divideLocal() will get better results average.



public class TestDivide {
    public static void main(String[] args) {
        new TestDivide();
    }
   
    public TestDivide() {
        Vec vec = new Vec();
        long end = 0;
        long start = 0;
        int i = 0;
       
        start = System.nanoTime();
        for (i = 0; i < 10000000; i++) {
            vec.divideLocal(1.01f);
        }
        end = System.nanoTime();
        System.out.println("duration: " +(end-start)/1000.0f/1000.0f +" ms");

//        start = System.nanoTime();
//        for (i = 0; i < 10000000; i++) {
//            vec.divideLocalSimple(1.01f);
//        }
//        end = System.nanoTime();
//        System.out.println("duration: " +(end-start)/1000.0f/1000.0f +" ms");
    }
   
    public class Vec {
        private float x = Float.MAX_VALUE;
        private float y = Float.MAX_VALUE;
        private float z = Float.MAX_VALUE;
       
        public void divideLocal(float scalar) {
            scalar = 1/scalar;
            x *= scalar;
            y *= scalar;
            z *= scalar;
        }
       
        public void divideLocalSimple(final float scalar) {
            x /= scalar;
            y /= scalar;
            z /= scalar;
        }
    }
}

edit: removed previous post … never mind i think i know now what you mean :slight_smile: