what is the fastest way to determine if a number is odd or even? TestFastestWayToDetermineOddOrEvenNumbers((int.MaxValue / 100000)) Ĭonsole.WriteLine("# Overall End Time: " + end.ToLongTimeString()) Ĭonsole.WriteLine("# Overall Run Time: " + (end - start)) TestFastestWayToDetermineOddOrEvenNumbers((int.MaxValue / 1000) - 1) TestFastestWayToDetermineOddOrEvenNumbers((int.MaxValue / 10)) TestFastestWayToDetermineOddOrEvenNumbers((int.MaxValue)) □Ĭonsole.WriteLine("# Overall Start Time: " + start.ToLongTimeString()) Obviously results may vary, and you should test on your system before micro-optimizing this functionality in your C#. After seeing my results, I don’t know why someone would use anything else unless you want to put in the code used for T5 with all its bit shifting to make it look like you’re doing some heavy-duty coding. Should you need to do a few hundred million checks, definitely keep using the modulus operator. It also performed the fastest on my machine. Personally I’ll keep using the modulus operator because let’s face it: it’s easy to read, maintain, and understand what the coder is trying to do. On my system, unless someone spots a flaw in my test code, and unless you have to check more than 2,147,482 numbers in one go, it really makes no significant performance difference which method is used for anywhere up to a few thousand conversions. Should these results change your coding methods? T4 using the ((x/2) * 2) = x technique performed just as well as T2 and T5 with their bitwise operations all the way up to 2 billion runs. I was fully expecting the bitwise operation to surpass it, and am not really curious as to why the bitwise and operator is slower.įor second place, there appears to be no dominating technique. There was only one instance where it came second, and not by much. The modulus operator, much to my surprise, performed the fastest. Winner marked in green second place marked in yellow. Lower numbers indicate faster performance. Let’s see what happened on my machine over multiple runs.Īll times are indicated in minutes:seconds.milliseconds format. □īefore starting, my hypothesis was that I expected the bitwise ampersand & technique to be the fastest. The test was run for each technique over the following number of numbers:īelow 21,474, the difference in results were negligible. The exe file was installed and run on an Alienware M17X R3 running Windows 7 64-bit with 16 GB memory on an i7-2820QM processor. The code assumes all numbers are positive integers.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |