How to speed up this code when converting float to string?

  • A+
Category:Languages

I have profiled my unit test and the majority of the time the application is running is spent on this section of code. It is a function that converts a float to a string. How can I rewrite the code below to have a better speed performance?

Am I misreading the report and the bottleneck is somewhere else?

The profile reports states:

Total CPU % = 13.02% , Self CPU % .07, Total CPU(ms) 769, Self CPU out of 100 percent 769 ms.

769 out of 5907 samples.

std::string FloatToScientificString(float val, int width, int precision) {     std::stringstream buffer;     buffer << std::scientific << std::setw(width) << std::setprecision(precision) << std::setfill(' ') << val;     return buffer.str(); } 

 


If using an external library to achieve this goal is possible, you can go with fmtlib (this library will probably make it into the standard), which claims to be faster than std::stringstream-based approaches (see their benchmarks).

#include <fmt/format.h>  std::string FloatToScientificString(float val, int width, int precision) {     return fmt::format("{:>{}.{}e}", val, width, precision); } 

This should return an identical string as your original function, and you don't sacrifice type safety as with std::sprintf approaches.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: