Converting double to char* in C++ with high performance

后端 未结 8 1539
野趣味
野趣味 2020-12-15 04:23

My application needs to convert double values to char* to write to a pipe that accepts only characters. The usual ways of doing this are using the sprintf() functio

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 04:43

    The slow part of sprintf on your system may not necessarily be converting the double, but parsing the format string. That might be good news for you as that is something that you could optimize away.

    Additionally, try hard to document all the knowledge you have about range, accuracy, and nature of the double values that you need to process, and use it to develop a special algorithm.

    Assuming your inputs are never subnormal numbers, use a known fixed precision and accuracy, a relatively high performing result may look like this:

    itoa((int)((f + 0.00001) * 10000))
    

    However, the sprintf and ostream approaches you are already aware of are the only solutions that are completely general and portable.

提交回复
热议问题