Frage

What is the faster between the two following code? why? In which case one can be preferred to the other?

double x = (a + b) >> 1
double x = (a + b) / 2.0
War es hilfreich?

Lösung 3

As others have said, the two statements produce different results, especially if (a + b) is an odd value.

Also, according to the language, a and b must be integral values in order to satisfy the shifting operation.

If a and b differ in type between the two statements, you are comparing apples to elephants.

Given this demo program:

#include <iostream>
#include <cstdlib>
#include <cmath>

using std::cout;
using std::endl;

int main(void)
{
    const unsigned int a = 5;
    const unsigned int b = 8;

    double x = (a + b) >> 1;
    cout << x << endl;
    double y = (a + b) / 2.0;
    cout << y << endl;

    return EXIT_SUCCESS;
}

The output:
6
6.5

Based on this experiment, the comparison is apples to oranges. The statement involving shifting is a different operation that dividing by a floating point number.

As far as speed goes, the second statement is slower because the expression (a + b) must be converted to double before applying the division. The division is floating point, which may be slow on platforms without hardware floating point support.

You should not concern yourself on the execution speed of either statement. Of more importance is the correctness and robustness of the program. For example, the two statements above provide different results, which is a very important concern for correctness.

Most Users would wait for a program to produce correct results than have a quick program producing incorrect results or behavior (nobody is in a hurry for a program to crash).

Management would rather you spend time completing the program than wasting time optimizing portions of the program that are executed infrequently.

Andere Tipps

These do different things so pick the one with the functionality you like: Truncating the result down or returning the 0.5 fraction.

"Premature optimization is root of all evil". Use what is more readable, when you have perfomance issue first look for algorithms and data structures, where you can get most perfomance gain, then run profiler and optimize where is necessary.

If a or b is a double or float, shifting will produce incorrect results.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top