问题
I am wondering whether "all" C++ formatting libraries eventually fall back to a *sprintf
function to format numbers.
I am asking this because:
- Looking at the iostreams library that comes with Visual C++, I can see that numbers input into a stream will eventuall be formatted with
sprintf_s
. - Boost.Format just uses the available iostreams library as far as I can tell.
- FastFormat eventually uses
vsprintf
to format a number.
So, are there iostreams implementations that do not use *sprintf and do the formatting themselves? Are there other formatting libraries that do not forward formatting of numbers to *sprintf family of functions?
I would appreciate answers in the form of:
- No: implementation XY uses ABC to format numbers
- Yes: all other (e.g. iostreams) implementations I know (X, Y, Z) also forward number formatting to stdio, because ...
Please avoid overly speculative answers.
回答1:
Boost Spirit doesn't use *printf, as can be seen from the code (real.hpp and int.hpp) and the benchmarks for e.g. ints and doubles.
The benchmark pits Boost Spirit Karma's generators against Boost.Format against sprintf and std::stringstream. Only for gcc compilers does the performance of sprintf come close in that benchmark. Otherwise, Boost Spirit is the clear winner.
- http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/karma/performance_measurements/numeric_performance.html
回答2:
No, at least this formatting library has its own implementation of integer formatting. It uses snprintf
only for floating-point numbers, but there are plans to use double-conversion for better performance. Currently the performance of this library is close to that of printf according to this benchmark. I wrote this blog post explaining how this was possible without sacrificing type safety.
Note that the benchmarks of Boost Karma are a bit misleading because they compare formatting like printf
to double-to-string conversion like dtoa. The difference is that the former gives you more control over output and does more work at runtime to process format specification.
Disclaimer: I'm the author of the mentioned formatting library.
来源:https://stackoverflow.com/questions/7684472/do-c-formatting-libraries-generally-fall-back-to-sprintf-for-numeric-formatti