在 C++11 中:
string s = std::to_string(42);
几周前我做了一个基准测试,得到了这些结果(使用当前 Xcode 附带的 clang 和 libc++):
stringstream took 446ms
to_string took 203ms
c style took 170ms
使用以下代码:
#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;
}