Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading