Fastest C++ way to convert float to string

后端 未结 2 668
独厮守ぢ
独厮守ぢ 2021-02-15 17:53

I have encountered problem of converting float to string where to_string is too slow for me as my data might involves few millions floats.

I already have so

2条回答
  •  天命终不由人
    2021-02-15 18:58

    Here are some of the fastest algorithms for converting floating point numbers into decimal string representation:

    • Grisu by Florian Loitsch: Printing Floating-Point Numbers Quickly and Accurately with Integers
    • Ryū by Ulf Adams: Ryū: fast float-to-string conversion
    • Schubfach by Raffaello Giulietti: The Schubfach way to render doubles
    • Dragonbox by Junekey Jeon: Dragonbox: A New Floating-Point Binary-to-Decimal Conversion Algorithm

    At the time of writing Dragonbox is the fastest of these methods, followed by Schubfach, then a variation of Grisu called Grisu-Exact (not to be confused with Grisu2 and Grisu3) and then Ryū:

    An implementation of Dragonbox is available here. It is also included in the {fmt} library integrated into a high-level formatting API. For maximum performance you can use format_to with a stack-allocated buffer, for example:

    fmt::memory_buffer buf;
    fmt::format_to(buf, "{}", 4.2);
    // buf.data() returns a pointer to the formatted data & buf.size() gives the size
    

提交回复
热议问题