【发布时间】:2011-04-29 10:26:09
【问题描述】:
可能重复:
Fastest way to read numerical values from text file in C++ (double in this case)
#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
流:1389
更新:删除下划线,环境:win7+vc10
【问题讨论】:
-
尝试使用 boost::spirit 代替。
-
那些双下划线名称在用户编写的代码中是非法的。如果 stringstreams 对你来说太慢 - 你有答案 - 使用 strtod。字符串流主要是为了方便和类型安全,而不是速度。
-
流将收集输入,然后最终调用 strtold 进行转换。让它变得更快!
-
它是哪个编译器?也许 STL 的 stlport 实现会比附带的更快(但不要指望击败 strtod,这是不可能的)。
-
@unapersson 双下划线名字是从别处抄来的,懒得修改
标签: c++ performance parsing