Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Multiplication Faster Than Comparison in .NET?

Good morning, afternoon or night,

Up until today, I thought comparison was one of the basic processor instructions, and so that it was one of the fastest operations one can do in a computer... On the other hand I know multiplication in sometimes trickier and involves lots of bits operations. However, I was a little shocked to look at the results of the following code:

Stopwatch Test = new Stopwatch();

int     a = 0;
int     i = 0, j = 0, l = 0;
double  c = 0, d = 0;

for (i = 0; i < 32; i++)
{
    Test.Start();

    for (j = Int32.MaxValue, l = 1; j != 0; j = -j + ((j < 0) ? -1 : 1), l = -l)
    {
        a = l * j;
    }

    Test.Stop();

    Console.WriteLine("Product: {0}", Test.Elapsed.TotalMilliseconds);
    c += Test.Elapsed.TotalMilliseconds;

    Test.Reset();
    Test.Start();

    for (j = Int32.MaxValue, l = 1; j != 0; j = -j + ((j < 0) ? -1 : 1), l = -l)
    {
        a = (j < 0) ? -j : j;
    }

    Test.Stop();

    Console.WriteLine("Comparison: {0}", Test.Elapsed.TotalMilliseconds);
    d += Test.Elapsed.TotalMilliseconds;

    Test.Reset();
    }

    Console.WriteLine("Product: {0}", c / 32);
    Console.WriteLine("Comparison: {0}", d / 32);
    Console.ReadKey();
}

Result:

Product: 8558.6
Comparison: 9799.7

Quick explanation: j is an ancillary alternate variable which goes like (...), 11, -10, 9, -8, 7, (...) until it reaches zero, l is a variable which stores j's sign, and a is the test variable, which I want always to be equal to the modulus of j. The goal of the test was to check whether it is faster to set a to this value using multiplication or the conditional operator.

Can anyone please comment on these results?

Thank you very much.

like image 731
Miguel Avatar asked Feb 24 '23 19:02

Miguel


1 Answers

Your second test it's not a mere comparison, but an if statement.

That's probably translated in a JUMP/BRANCH instruction in CPU, involving branch prediction (with possible blocks of the pipeline) and then is likely slower than a simple multiplication (even if not so much).

like image 144
digEmAll Avatar answered Mar 06 '23 04:03

digEmAll