Fastest C++ way to convert float to string

后端 未结 2 618
独厮守ぢ
独厮守ぢ 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:55

    An optimization that comes in mind is to not directly use to_string, which creates a new string every time you call it. You probably end up copying that string too, which is not so efficient.

    What you could do is to allocate a char buffer big enough to store all the string representations that you need, then use printf

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

    reusing the same buffer all the time. If you limit the precision of your floats to a fixed amount of decimals, you can compute the offset to which your float is represented in the array.

    for example if we only had an array of values:

    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
    

    for clarification your char_array will look like:

    1.2000\02.4324\0...
    

提交回复
热议问题