performance - c++ stringstream is too slow, how to speed up? -
possible duplicate:
fastest way read numerical values text file in c++ (double in 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(); (int i=0; i<1000000; ++i) double x = str2dou1(str); tend=clock(); cout << tend-tstart << endl; cout << "sstream: "; tstart=clock(); (int i=0; i<1000000; ++i) double x = str2dou2(str); tend=clock(); cout << tend-tstart << endl; return 0; }
strtod: 405
sstream: 1389
update: remove undersocres, env: win7+vc10
c/c++ text number formatting slow. streams horribly slow c number parsing slow because it's quite difficult correct down last precision bit.
in production application reading speed important , data known have @ 3 decimal digits , no scientific notation got vast improvement hand-coding floating parsing function handling sign, integer part , number of decimals (by "vast" mean 10x faster compared strtod
).
if don't need exponent , precision of function enough code of parser similar 1 wrote then. on pc it's 6.8 times faster strtod , 22.6 times faster sstream.
double parsefloat(const std::string& input) { const char *p = input.c_str(); if (!*p || *p == '?') return nan_d; int s = 1; while (*p == ' ') p++; if (*p == '-') { s = -1; p++; } double acc = 0; while (*p >= '0' && *p <= '9') acc = acc * 10 + *p++ - '0'; if (*p == '.') { double k = 0.1; p++; while (*p >= '0' && *p <= '9') { acc += (*p++ - '0') * k; k *= 0.1; } } if (*p) die("invalid numeric format"); return s * acc; }
Comments
Post a Comment