Good morning day or night
Until today, I thought that comparison was one of the main instructions of the processor, and therefore it was one of the fastest operations that can be done on a computer ... On the other hand, I know that multiplication is sometimes more complicated and requires a lot of bit 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 a helper alternative variable that goes like (...), 11, -10, 9, -8, 7, (...) until it reaches zero, l is a variable that stores the sign of j , and a is a test variable that I want to always be equal to module j . The purpose of the test was to check whether it is faster to set this value of a using multiplication or a conditional operator.
Can anyone comment on these results?
Thank you very much.
source share