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

前端 未结 8 2047
误落风尘
误落风尘 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:59

    For an example, here is a very fast number parser from one of my projects. It only handles a very small subset of the actual features of the Standard Library numeric parsing.

    uint64_t mystrtol( char *&pen, uint64_t val = 0 ) {
        for ( char c; ( c = *pen ^ '0' ) <= 9; ++ pen ) val = val * 10 + c;
        return val;
    }
    
    value_t mystrtof( char *&pen ) {
        static value_t const exp_table[]
         = { 1e5, 1e4, 1e3, 1e2, 10, 1, 0.1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13, 1e-14, 1e-15, 1e-16, 1e-17 },
         * exp_lookup = & exp_table[ 5 ];
    
        while ( iswspace( * ++ pen ) ) ;
        //if ( *pen == '-' ) ++ pen; // don't think we ever care about negative numbers
        uint64_t val = mystrtol( pen );
        int neg_exp = 0;
        if ( *pen == '.' ) { // mainly happens when val = 0
            char const *fracs = ++ pen;
            val = mystrtol( pen, val );
            neg_exp = pen - fracs;
        }
        if ( ( *pen | ('E'^'e') ) == 'e' ) {
            neg_exp += *++pen == '-'? mystrtol( ++ pen ) : - mystrtol( ++ pen );
        }
        return val * exp_lookup[ neg_exp ];
    }
    

提交回复
热议问题