可能重複:
Fastest way to read numerical values from text file in C++ (double in this case)C++ stringstream太慢了,怎麼加快?
#include <ctime>
#include <cstdlib>
#include <string>
#include <sstream>
#include <iostream>
#include <limits>
using namespace std;
static const double NAN_D = numeric_limits<double>::quiet_NaN();
void die(const char *msg, const char *info)
{
cerr << "** error: " << msg << " \"" << info << '\"';
exit(1);
}
double str2dou1(const string &str)
{
if (str.empty() || str[0]=='?') return NAN_D;
const char *c_str = str.c_str();
char *err;
double x = strtod(c_str, &err);
if (*err != 0) die("unrecognized numeric data", c_str);
return x;
}
static istringstream string_to_type_stream;
double str2dou2(const string &str)
{
if (str.empty() || str[0]=='?') return NAN_D;
string_to_type_stream.clear();
string_to_type_stream.str(str);
double x = 0.0;
if ((string_to_type_stream >> x).fail())
die("unrecognized numeric data", str.c_str());
return x;
}
int main()
{
string str("12345.6789");
clock_t tStart, tEnd;
cout << "strtod: ";
tStart=clock();
for (int i=0; i<1000000; ++i)
double x = str2dou1(str);
tEnd=clock();
cout << tEnd-tStart << endl;
cout << "sstream: ";
tStart=clock();
for (int i=0; i<1000000; ++i)
double x = str2dou2(str);
tEnd=clock();
cout << tEnd-tStart << endl;
return 0;
}
的strtod:405
sstream:1389
更新:刪除undersocres,ENV:WIN7 + VC10
嘗試使用boost :: spirit代替。 – W55tKQbuRu28Q4xv 2011-04-29 10:30:28
這些雙下劃線名稱在用戶編寫的代碼中是非法的。如果stringstream對你來說太慢 - 你有答案 - 使用strtod。 stringstreams主要是爲了方便和類型安全,而不是速度。 – 2011-04-29 10:47:29
流將收集輸入,然後最終調用strtold進行轉換。讓它很難變得更快! – 2011-04-29 11:00:03