Home

float
Dennis Lang
lang.dennis @ comcast.net

Time to Convert Ascii String to Floating Point Number
Updated: 7-Jan-2015

While parsing xml, I discovered that converting a textual floating point value back to its binary form was expensive. Here are the results of various conversion solutions. Test run on Windows7/x64, HP xw8600 dual quad core Intel Xeon e5440 @ 2.83Ghz, using Visual Studio 2013 update 4.

ascii-to-float
Ratio is elapsed seconds divided by AToF time.
Release VS2013 on HP xw8600 Xeon E5440 2.83Ghz
Test Seconds Ratio Seconds Ratio
 VS2013/x86 VS2013/x64
AToF0.156 1.00 0.140 1.00
atof0.249 1.60 0.234 1.67
strtod0.250 1.60 0.234 1.67
scanf0.468 3.00 0.406 2.90
strStream5.99038.40 4.78934.21
stringStream6.08539.01 4.93035.21
(fewer seconds is faster, each group in order fastest to slowwest)

AToF is a hand written version of the standard atof(). I found the code on the web at:

The following link no longer works. I included the code in the zip file below.

http://www.bsdlover.cn/study/UnixTree/V7/usr/src/libc/gen/atof.c.html

I am assuming the default atof() and strtod() are slower because they deal with language/locality issues.
StringStream is the slowest way to convert a string back to its binary form.

WARNING - atof() and strtod() internally call strlen() on the input string. If your input string is a pointer to a region inside a very large text document, it will take a long time to calculate the string length. I had a case where I was extracting floating point values from a file I memory mapped. To improve performance, I had to zero terminate each floating point character sequence. Since I did not want to alter the memory mapped file, I copied the text to a local buffer.


I created a similar test in the reverse direction and here are the results: float-to-ascii
Ratio is elapsed seconds divided by fcvt time.
Release VS2013 on HP xw8600 Xeon E5440 2.83Ghz

Test Seconds Ratio Seconds Ratio
 VS2013/x86 VS2013/x64
fcvt 0.6081.000.5461.00
sprintf 0.8581.410.7641.40
gcvt 1.2172.001.0922.00
strStream 2.8864.752.0913.83
stringStream 2.9334.822.0283.71
(fewer seconds is faster, each group in order fastest to slowwest)

Conclusion: fcvt is fastest

Source code to both conversions test suites:

float_conversion_perf.zip



Please visit home page for more programs and performance information.