有没有办法解析INT到字符串/ char*而不使用流?

Fal*_*per 2 c++ parsing

关于从int转换为字符串的帖子很多,但它们都涉及到只是打印到屏幕或使用ostringstream.

我正在使用ostringstream,但我的公司不希望我使用任何流,因为它有可怕的运行时.

我是在C++文件中这样做的.

我的问题是,我将在执行过程中创建数百万个流,写入缓冲区,然后将内容复制到字符串中,如下所示:

ostringstream OS;
os << "TROLOLOLOLOL";
std::string myStr = os.str();
Run Code Online (Sandbox Code Playgroud)

有冗余,因为它使这个缓冲区然后全部复制它.啊!

luc*_*nte 6

在C++ 11中:

string s = std::to_string(42);
Run Code Online (Sandbox Code Playgroud)

几个星期前我做了一个基准测试,得到了这些结果(使用当前Xcode附带的clang和libc ++):

stringstream took 446ms
to_string took 203ms
c style took 170ms
Run Code Online (Sandbox Code Playgroud)

使用以下代码:

#include <iostream>
#include <chrono>
#include <sstream>
#include <stdlib.h>

using namespace std;

struct Measure {
  chrono::time_point<chrono::system_clock> _start;
  string _name;

  Measure(const string& name) : _name(name) {
    _start = chrono::system_clock::now();
  }

  ~Measure() {
    cout << _name << " took " << chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now() - _start).count() << "ms" << endl;
  }
};



int main(int argc, const char * argv[]) {
  int n = 1000000;
  {
    Measure m("stringstream");
    for (int i = 0; i < n; ++i) {
      stringstream ss;
      ss << i;
      string s = ss.str();
    }
  }
  {
    Measure m("to_string");
    for (int i = 0; i < n; ++i) {
      string s = to_string(i);
    }
  }
  {
    Measure m("c style");
    for (int i = 0; i < n; ++i) {
      char buff[50];
      snprintf(buff, 49, "%d", i);
      string s(buff);
    }
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 使用相同的基准测试,但将流创建移到循环外并说`ss.str("");`每次迭代清除它,我得到190ms运行时而不是`to_string`的191ms.`snprintf`在169ms时略快一些. (2认同)