Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster, multiplication or subtraction? [closed]

I'm currently doing a University project which is marked heavily upon the speed and efficiency of my solution. Minor changes I make to the code have massive impacts, as the particular function I am writing is called many hundreds of thousands of times.

I have written the main functionality of my project now, and am currently in the process of optimising everything I possibly can. One particular part of my code that I am questioning looks like this:

array[i] *= -1;

Which I was considering optimising to:

array[i] = 0 - array[i];

Would changing this code actually affect the speed? Is a subtraction operation faster than a multiplication operation? Or is this kind of issue a thing of the past?

like image 303
Jamie Avatar asked Nov 22 '12 13:11

Jamie


2 Answers

Overlooking the fact that you should probably use this instead:

array[i] = -array[i];

as it's much clearer IMO since it directly states intent, lets check what the compiler does (GCC 4.7.2 on x86-64) for this program:

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t t = time(NULL);
    t *= -1;
    return 0;
}
gcc -S mult.c -o 1.s

And for this:

#include <stdio.h>
#include <time.h>

int main(void)
{
    time_t t = time(NULL);
    t = 0 - t;
    return 0;
}
gcc -S sub.c -o 2.s

Now compare the two assembly outputs:

diff 1.s 2.s

Nothing is printed. The compiler generated the same exact code for both versions. So the answer is: it doesn't matter what you use. The compiler will choose whatever is fastest. This is a pretty easy optimization to make (if you can even call it an optimization), so we can assume that virtually every compiler out there will pick the fastest way to do it for a given CPU architecture.

For reference, the generated code is:

int main()
{
    time_t t = time(NULL);
       mov    edi,0x0
       call   12 
       mov    QWORD PTR [rbp-0x8],rax

    t *= -1;
       neg    QWORD PTR [rbp-0x8]

    t = 0 - t;
       neg    QWORD PTR [rbp-0x8]

    return 0;
       mov    eax,0x0
}

In both cases, it uses NEG to negate the value. t *= -1 and t = 0 - t both generate:

neg QWORD PTR [rbp-0x8]
like image 62
Nikos C. Avatar answered Sep 20 '22 18:09

Nikos C.


There's only one sane way of going about optimization, and that is by measuring the performance of your application. A good profiler will be able to tell you a lot, but simply timing the execution of your program and various modifications can also be of great help. I'd go with the profiler first, though to find where the bottlenecks are.

As for your specific question, as others have pointed out this will be highly architecture dependant.

like image 38
harald Avatar answered Sep 19 '22 18:09

harald