我遇到了将 float 转换为字符串的问题,其中 to_string
对我来说太慢了,因为我的数据可能涉及几百万个 float 。
我已经在 how to write those data out fast 上找到了解决方案.
然而,在解决了那个问题之后,我很快意识到,float 到 string 的转换留下了很大的影响。
那么,除了使用其他非标准库之外,还有什么想法或解决方案吗?
最佳答案
以下是一些将 float 转换为十进制字符串表示形式的最快算法:
- Florian Loitsch 的 Grisu:Printing Floating-Point Numbers Quickly and Accurately with Integers
- 乌尔夫亚当斯的 Ryū:Ryū: fast float-to-string conversion
- Raffaello Giulietti 的 Schubfach:The Schubfach way to render doubles
- Junekey Jeon 的 Dragonbox:Dragonbox: A New Floating-Point Binary-to-Decimal Conversion Algorithm
在撰写本文时,Dragonbox 是这些方法中最快的,其次是 Schubfach,然后是 Grisu 的变体 Grisu-Exact(不要与 Grisu2 和 Grisu3 混淆),然后是 Ryū:
Dragonbox 的实现可用 here .它也包含在 the {fmt} library 中集成到高级格式化 API 中。为了获得最佳性能,您可以将 format_to
与堆栈分配的缓冲区一起使用,例如:
fmt::memory_buffer buf;
fmt::format_to(buf, "{}", 4.2);
// buf.data() returns a pointer to the formatted data & buf.size() gives the size
关于c++ - 将 float 转换为字符串的最快 C++ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29767027/