Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - What would be faster: multiplying or adding?

I have some code that is going to be run thousands of times, and was wondering what was faster. array is a 30 value short array which always holds 0, 1 or 2.

result = (array[29] * 68630377364883.0)
       + (array[28] * 22876792454961.0)
       + (array[27] * 7625597484987.0)
       + (array[26] * 2541865828329.0)
       + (array[25] * 847288609443.0)
       + (array[24] * 282429536481.0)
       + (array[23] * 94143178827.0)
       + (array[22] * 31381059609.0)
       + (array[21] * 10460353203.0)
       + (array[20] * 3486784401.0)
       + (array[19] * 1162261467)
       + (array[18] * 387420489)
       + (array[17] * 129140163)
       + (array[16] * 43046721)
       + (array[15] * 14348907)
       + (array[14] * 4782969)
       + (array[13] * 1594323)
       + (array[12] * 531441)
       + (array[11] * 177147)
       + (array[10] * 59049)
       + (array[9]  * 19683)
       + (array[8]  * 6561)
       + (array[7]  * 2187)
       + (array[6]  * 729)
       + (array[5]  * 243)
       + (array[4]  * 81)
       + (array[3]  * 27)
       + (array[2]  * 9)
       + (array[1]  * 3)
       + (b[0]);

Would it be faster if I use something like:

if(array[29] != 0)
{
    if(array[29] == 1)
    {
        result += 68630377364883.0;
    }
    else
    {
        result += (whatever 68630377364883.0 * 2 is);
    }
}

for each of them. Would this be faster/slower? If so, by how much?

like image 985
noryb009 Avatar asked Mar 11 '26 03:03

noryb009


2 Answers

That is a ridiculously premature "optimization". Chances are you'll be hurting performance because you are adding branches to the code. Mispredicted branches are very costly. And it also renders the code harder to read.

Multiplication in modern processors is a lot faster than it used to be, it can be done a few clock cycles now.

Here's a suggestion to improve readability:

for (i=1; i<30; i++) {
    result += array[i] * pow(3, i);
}
result += b[0];

You can pre-compute an array with the values of pow(3, i) if you are really that worried about performance.

like image 120
NullUserException Avatar answered Mar 12 '26 16:03

NullUserException


First, on most architectures, mis-branching is very costly (depending on the execution pipeline depth), so I bet the non-branching version is better.

A variation on the code may be:

result = array[29];
for (i=28; i>=0; i--)
    result = result * 3 + array[i];

Just make sure there are no overflows, so result must be in a type larger than 32-bit integer.

like image 26
ysap Avatar answered Mar 12 '26 16:03

ysap