如何改进带逗号性能的格式编号? [英] How can I improve formatting number with commas performance?

查看:132
本文介绍了如何改进带逗号性能的格式编号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下方法来格式化带有逗号的数字:

I'm using the following method to format a number with commas:

template<class T>
static std::string FormatNumberWithCommas(T value, int numberOfDecimalPlaces = 0)
{
    std::stringstream ss;
    ss.imbue(std::locale(""));
    ss.precision(numberOfDecimalPlaces);
    ss << std::fixed << value;
    return ss.str();
}

分析显示此方法相对于其他代码需要花费大量时间。具体来说,profiler已经识别了这一行:

Profiling has show this method to take a significant amount of time relative to other code. Specifically the profiler has identified the line:

ss.imbue(std::locale(""));

在这里我相信是 std :: locale )这需要很长时间。如何提高这种方法的性能?

And within that I believe it is the std::locale("") that is taking long. How can I improve the performance of this method? If it requires using something other than stringstream or doing something semi-hacky in this particular method I'm open to it.

推荐答案

如果需要使用除了stringstream之外的其他东西,或者在这个特定的方法中做半成品,您可以先将字符串流设为一个静态变量:

You could start by making the string stream a static variable:

{
  static std::stringstream ss;
  static bool ss_init = false;
  static std::string emtpy_string;
  if (!ss_init) { ss.imbue(std::locale("")); ss_init = true; }

  ss.str(empty_string);
  // ...
}

如果这仍然是瓶颈,可以查看 fastformat 这样的替代格式库。

If that's still a bottleneck, you could look at an alternative formatting library like fastformat.

这篇关于如何改进带逗号性能的格式编号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆