C++ iostream vs. C stdio performance/overhead

后端 未结 3 1118
旧巷少年郎
旧巷少年郎 2020-12-18 06:30

I\'m trying to comprehend how to improve the performance of this C++ code to bring it on par with the C code it is based on. The C code looks like this:

#inc         


        
3条回答
  •  遥遥无期
    2020-12-18 07:11

    Update: I did some more testing and (if you have enough memory) there is a surprisingly simple solution that - at least on my machine with VS2015 - outperforms the c-solution: Just buffer the file in a stringstream.

    ifstream input("biginput.txt");
    std::stringstream buffer;
    buffer << input.rdbuf();
    point p;
    while (buffer >> p) {
        i++
    }
    

    So the problem seems to be not so much related to the c++ streaming mechanism itself, but to the internals of ifstream in particular.


    Here is my original (outdated) Answer: @Frederik already explained, that the performance mismatch is (at least partially) tied to a difference in functionality.

    As to how to get the performance back: On my machine with VS2015 the following runs in about 2/3 of the time the C-solution requries (although, on my machine, there is "only" a 3x performance gap between your original versions to begin with):

    istream &operator >> (istream &in, point &p) {
        thread_local std::stringstream ss;
        thread_local std::string s;
    
        if (std::getline(in, s)) {
            ss.str(s);
            ss >> p.x >> p.y;
        }
        return in;
    }
    

    I'm not too happy about the thread_local variables, but they are necessary to eliminate the overhead of repeatedly dynamic memory allocation.

提交回复
热议问题