Some Methods to Get the Number of Digits in An Integer, and Their Performance

16 Feb

Sometimes, we need to know the number of digits in an integer. There are many methods, which could do this work well. Here we list some of them, and compare their performance in different circumstances. Firstly, we post the source code of the testing program.

We tested the performance on Linux with Intel(R) Xeon(R) E5620 and 12G memory. The result is as following:

Method

Total Running Time (for 0xFFFFFF Rounds), in seconds

Num=010xFFFF0xFFFFFFFF0xFFFFFFFFFFFF0xFFFFFFFFFFFFFFFF
Log10N/A1.511.641.461.501.53
Sprintf2.392.172.543.123.684.31
Division0.060.060.952.073.184.30
Brute0.350.350.310.230.160.07

The cost of log10 method is stable, no matter the number is big or small.

The sprintf method is always the slowest solution.

The division method is quick when the number is small.

The brute force method is ugly, but always efficient.

More discussion and an optimization solution for worst cases are in the next article here.

Leave a Reply

Your email address will not be published. Required fields are marked *