Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's more costly on current CPUs: arithmetic operations or conditionals?

20-30 years ago arithmetic operations like division were one of the most costly operations for CPUs. Saving one division in a piece of repeatedly called code was a significant performance gain. But today CPUs have fast arithmetic operations and since they heavily use instruction pipelining, conditionals can disrupt efficient execution. If I want to optimize code for speed, should I prefer arithmetic operations in favor of conditionals?

Example 1

Suppose we want to implement operations modulo n. What will perform better:

int c = a + b;
result = (c >= n) ? (c - n) : c;

or

result = (a + b) % n;

?

Example 2

Let's say we're converting 24-bit signed numbers to 32-bit. What will perform better:

int32_t x = ...;
result = (x & 0x800000) ? (x | 0xff000000) : x;

or

result = (x << 8) >> 8;

?

like image 699
Petr Avatar asked Feb 09 '13 15:02

Petr


People also ask

Which operation is expensive?

Division and modulus are more than twice as expensive as multiplication (a weight 10). The division by two or a multiple of two is always a trick, but not much more can be done without having side-effects. If you can replace division by multiplication, you do get a speed-up of more than two.

How many types of arithmetic operations are available in a computer?

Data is manipulated by using the arithmetic instructions in digital computers. Data is manipulated to produce results necessary to give solution for the computation problems. The Addition, subtraction, multiplication and division are the four basic arithmetic operations.


2 Answers

All the low hanging fruits are already picked and pickled by authors of compilers and guys who build hardware. If you are the kind of person who needs to ask such question, you are unlikely to be able to optimize anything by hand.

While 20 years ago it was possible for a relatively competent programmer to make some optimizations by dropping down to assembly, nowadays it is the domain of experts, specializing in the target architecture; also, optimization requires not only knowing the program, but knowing the data it will process. Everything comes down to heuristics, tests under different conditions etc.

Simple performance questions no longer have simple answers.

like image 93
fdreger Avatar answered Sep 23 '22 16:09

fdreger


If you want to optimise for speed, you should just tell your compiler to optimise for speed. Modern compilers will generally outperform you in this area.

I've sometimes been surprised trying to relate assembly code back to the original source for this very reason.

Optimise your source code for readability and let the compiler do what it's best at.

like image 21
paxdiablo Avatar answered Sep 26 '22 16:09

paxdiablo