Fastest way to read numerical values from text file in C++ (double in this case)

前端 未结 8 2056
误落风尘
误落风尘 2020-12-05 03:08

Currently, my code is simply this:

void ReadFile(double Cst[][1000], char* FileName, int height)

FILE* ifp;
double value;
int nRead = 0;
int mRead = 0;

//o         


        
8条回答
  •  借酒劲吻你
    2020-12-05 03:52

    C/C++ parsing numbers from text is very slow. Streams are horribly slow but even C number parsing is slow because it's quite difficult to get it correct down to the last precision bit.

    In a production application where reading speed was important and where data was known to have at most three decimal digits and no scientific notation I got a vast improvement by hand-coding a floating parsing function handling only sign, integer part and any number of decimals (by "vast" I mean 10x faster compared to strtod).

    If you don't need exponent and the precision of this function is enough this is the code of a parser similar to the one I wrote back then. On my PC it's now 6.8 times faster than strtod and 22.6 times faster than 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;
    }
    

提交回复
热议问题