将浮点数转换为字符串的最快 C++ 方法

Fastest C++ way to convert float to string

我遇到了将浮点数转换为字符串的问题,其中 to_string 对我来说太慢了,因为我的数据可能涉及几百万个浮点数。

我已经在 上找到了解决方案。

但是,在解决了那个问题之后,我很快意识到,float 到 string 的转换留下了很大的影响。

那么,除了使用其他非标准库之外,还有什么想法或解决方案吗?

想到的一个优化是不直接使用to_string,每次调用都会创建一个新的字符串。 您可能最终也复制了该字符串,这效率不高。

你可以做的是分配一个足够大的 char 缓冲区来存储你需要的所有字符串表示,然后使用 printf

http://www.cplusplus.com/reference/cstdio/printf/

一直重复使用同一个缓冲区。 如果将浮点数的精度限制为固定的小数位数,则可以计算浮点数在数组中表示的偏移量。

例如,如果我们只有一个值数组:

index = 1;
float f = value[index];
//corrresponding 6 chars float
const char* s = char_array[index*1];
//the representation will start at position 6, and it will be null terminated so you can use it as a string

澄清一下,您的 char_array 将如下所示:

1.2000.4324[=11=]...

以下是一些将浮点数转换为十进制字符串表示形式的最快算法:

在撰写本文时,Dragonbox 是这些方法中最快的,其次是 Schubfach,然后是 Grisu 的变体 Grisu-Exact(不要与 Grisu2 和 Grisu3 混淆),然后是 Ryū:

Dragonbox 的实现可用 here. It is also included in 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