C++ iostream vs. C stdio performance/overhead

后端 未结 3 1121
旧巷少年郎
旧巷少年郎 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:20

    What's causing a significant difference in performance is a significant difference in the overall functionality.

    I will do my best to compare both of your seemingly equivalent approaches in details.

    In C:

    Looping

    • Read characters until a newline or end-of-file is detected or max length (1024) is reached
    • Tokenize looking for the hardcoded white-space delimiter
    • Parse into double without any questions

    In C++:

    Looping

    • Read characters until one of the default delimiters is detected. This isn't limiting the detection to your actual data pattern. It will check for more delimiters just in case. Overhead everywhere.
    • Once it found a delimiter, it will try to parse the accumulated string gracefully. It won't assume a pattern in your data. For example, if there is 800 consecutive numeric characters and isn't a good candidate for the type anymore, it must be able to detect that possibility by itself, so it adds some overhead for that.

    One way to improve performance that I'd suggest is very near of what Peter said in above comments. Use getline inside operator>> so you can tell about your data. Something like this should be able to give some of your speed back, thought it's somehow like C-ing a part of your code back:

    istream &operator>>(istream &in, point &p) {
        char bufX[10], bufY[10];
        in.getline(bufX, sizeof(bufX), ' ');
        in.getline(bufY, sizeof(bufY), '\n');
        p.x = atof(bufX);
        p.y = atof(bufY);
        return in;
    }
    

    Hope it's helpful.

    Edit: applied nneonneo's comment

提交回复
热议问题