royal grasshopper
royal grasshopper

Reputation: 47

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

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 ?

Upvotes: 0

Views: 116

Answers (2)

Lundin
Lundin

Reputation: 214920

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

Upvotes: 6

John Bode
John Bode

Reputation: 123578

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.

Upvotes: 0

Related Questions