0

In my computer architecture class I just learned that running an algebraic expression involving multiplication through a multiplication circuit can be more costly than running it though an addition circuit, if the number of required multiplications are less than 3. Ex: 3x. If I'm doing this type of computation a few billion times, does it pay off to write it as: x + x + x or does the JIT optimizer optimize for this?

Sarah Szabo
  • 10,345
  • 9
  • 37
  • 60

1 Answers1

2

I wouldn't expect to be a huge difference on writing it one way or the other.

The compiler will probably take care of making all of those equivalent.

You can try each method and measure how long it takes, that could give you a good hint to answer your own question.

Here's some code that does the same calculations 10 million times using different approaches (x + x + x, 3*x, and a bit shift followed by a subtraction).

They seem to all take approx the same amount of time as measured by System.nanoTime.

Sample output for one run:

sum   : 594599531
mult  : 568783654
shift : 564081012

You can also take a look at this question that talks about how compiler's optimization can probably handle those and more complex cases: Is shifting bits faster than multiplying and dividing in Java? .NET?

Code:

    import java.util.Random;

    public class TestOptimization {

        public static void main(String args[]) {
            Random rn = new Random();
            long l1 = 0, l2 = 0, l3 = 0;
            long nano1 = System.nanoTime();
            for (int i = 1; i < 10000000; i++) {
                int num = rn.nextInt(100);
                l1 += sum(num);
            }
            long nano2 = System.nanoTime();
            for (int i = 1; i < 10000000; i++) {
                int num = rn.nextInt(100);
                l2 += mult(num);
            }
            long nano3 = System.nanoTime();
            for (int i = 1; i < 10000000; i++) {
                int num = rn.nextInt(100);
                l3 += shift(num);
            }
            long nano4 = System.nanoTime();
            System.out.println(l1);
            System.out.println(l2);
            System.out.println(l3);
            System.out.println("sum   : " + (nano2 - nano1));
            System.out.println("mult  : " + (nano3 - nano2));
            System.out.println("shift : " + (nano4 - nano3));
        }

        private static long sum(long x) {
            return x + x + x;
        }

        private static long mult(long x) {
            return 3 * x;
        }

        private static long shift(long x) {
            return (x << 2) - x;
        }

    }
Community
  • 1
  • 1
eugenioy
  • 11,825
  • 28
  • 35