Tuesday, August 9, 2011

Benchmarking: Number of digits in a number

I've been curious about benchmarking certain code to see if which methods are better but just never got around to it. This is my first attempt because I wanted to know the efficiency of my method.

The algorithm I am trying to test is to find the number of digits in a number (in my case of type long). Initially I tried to put in some hard-coded "random" numbers and the results came almost eventually with the mathematical approach to be slightly faster. Then I entered some larger numbers and the results became clearer.

Approach #1 (mathematically):
I used division until the value reached 0 to determine the length of the number.

Approach #2 (convert to string):
I used a ToString function to find the length of the string.

Code to Approach #1:
1:   public static int NumberOfDigits(long Number)  
2:      {  
3:        long temp = System.Math.Abs(Number);  
4:        int counter = 0;  
5:        while (temp > 0)  
6:        {  
7:          temp = temp / 10;  
8:          counter++;  
9:        }  
10:        if (Number == 0) { counter = 1; }  
11:        return counter;  
12:      }  


Code to Approach #2:
1:      public static int NumberOfDigits_V2(long Number)  
2:      {  
3:        string temp = System.Math.Abs(Number).ToString();  
4:        return temp.Length;  
5:      }  


Benchmark includes 105 different values including negative, zero, and positive values. Running 10,000,000 calculations of the preset 105 values.

The results in milliseconds:
#1
1387.0793
1733.0992

#2
1416.081
1806.1033

#3
1422.0813
1804.1032

Conclusion, converting to string takes longer than the actual calculations but both takes less than a fifth of a millisecond. The code for the string conversion is much simpler and may be preferable for more readability.

Tests can be run from http://www.dlastlee.com and type in run test1

No comments:

Post a Comment