开发者

Do C++ formatting libraries generally fall back to *sprintf for numeric formatting?

开发者 https://www.devze.com 2023-04-11 03:59 出处:网络
I am wondering whether \"all\" C++ formatting libraries eventually fall back to a *sprintf function to format numbers.

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 the开发者_JS百科mselves? 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.


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.

Do C++ formatting libraries generally fall back to *sprintf for numeric formatting?

  • http://www.boost.org/doc/libs/1_47_0/libs/spirit/doc/html/spirit/karma/performance_measurements/numeric_performance.html


No, for example the {fmt} library has its own implementation of integer and floating-point formatting which is much faster than common implementations of sprintf. These are the results of a double to string formatting benchmark (dtoa-benchmark) on one platform:

Do C++ formatting libraries generally fall back to *sprintf for numeric formatting?

As you can see {fmt} is ~20x faster than sprintf here.

Integer formatting is also faster but not as dramatically (up to 6-7x on Linux and macOS):

Do C++ formatting libraries generally fall back to *sprintf for numeric formatting?

Disclaimer: I'm the author of {fmt}.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号