Compare the computation speed of (a+b)*c and a*c+b*c

111 Views Asked by At

I've just learned that additive operation is faster than multiplicative operation in C. Therefore, I'm curious whether (a+b)*c would be calculated faster than a*c+b*c ?

2

There are 2 best solutions below

10
Lundin On

I've just learned that additive operation is faster than multiplicative operation in C

That's nonsense. There is nothing in the C language itself that affects this. Which is faster depends entirely on the instruction set (ISA) provided by the CPU.

Therefore, I'm curious whether (a+b)*c would be calculated faster than a*c+b*c

It is very likely that the optimizing compiler will generate the same machine code no matter which of those versions you write in the C code. Try out this code:

int add1 (int a, int b, int c)
{
  return (a+b)*c;
}

int add2 (int a, int b, int c)
{
  return a*c+b*c;
}

On gcc -O3 13.1 for x86_x64 I get 100% equivalent assembler code for both versions:

add1:
    lea     eax, [rdi+rsi]
    imul    eax, edx
    ret
add2:
    lea     eax, [rsi+rdi]
    imul    eax, edx
    ret
0
John Bode On

The only way to know for sure is to measure directly. You can look at the machine code, but that doesn't necessarily tell you how things will be processed; your system may execute operations in parallel.

Write up both versions, instrument the code to gather statistics (either through a profiler or manually), then run the computations several million times.