Home > Net >  Is there a faster way to multiply by 6 in C?
Is there a faster way to multiply by 6 in C?

Time:12-24

I am currently writing a program in C which needs to run as fast as possible and am currently looking at improving the speed of some of the calculations performed. I am aware that the slowest operations are multiplication and division, and I have replaced my multiplications/divisions by a power of 2 with left/right shifts.

I was wondering if I could do something similar for multiplication by 6, as it seems that this operation pops up a lot in my program. Regularly it is being multiplied by a number which is 1 or 0, and I feel there should be a good way to speed this up but can't think of any.

CodePudding user response:

Trust your compiler. Do not think too much about microoptimizations. They usually have an adverse effect. All versions compile to the same code:

int imul6(int x)
{
    int y = x   x;
    return y y y;
}


int imoul6_1(int n)
{
    return ((n << 1)   n) << 1;
}

int imul6_2(int x)
{
    return x x x x x x;
}

int imul6_3(int x)
{
    return x*6;
}

https://godbolt.org/z/vMos69PaM

CodePudding user response:

You can multiply number n by 6 to get m doing : m = ((n << 1) n) << 1

  • Related