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

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

    It seems to me you've written a lot of brittle code in the hope that it'll be super efficient. Before attempting all this code, have you even attempted the simple C++ idiomatic solution and determined that it's not fast enough?

    std::ifstream input("/path/to/file");
    if ( !input.is_open() ) {
        // handle error.
    }
    std::vector numbers;
    std::copy(std::istream_iterator(input),
        std::istream_iterator(), std::back_inserter(numbers));
    
    // Access item at position (i,j).
    double x = numbers[1000*j+i];
    

    Keep in mind that the developers behind your standard library vendor's implementation give their best at making this simple code as fast as possible. It's very likely you'll be able to reach your performance requirements with this trivial piece of code.

    On top of that, you get a bunch of freebies:

    1. cleans up automatically (manages memory and file handle);
    2. automatically resizes for larger inputs;
    3. checks for errors when parsing.

提交回复
热议问题