'printf' vs. 'cout' in C++

后端 未结 16 1752
梦如初夏
梦如初夏 2020-11-22 07:04

What is the difference between printf() and cout in C++?

16条回答
  •  野性不改
    2020-11-22 07:33

    TL;DR: Always do your own research, in regard of generated machine code size, performance, readability and coding time before trusting random comments online, including this one.

    I'm no expert. I just happened to overhear two co-workers talking about how we should avoid using C++ in embedded systems because of performance issues. Well, interesting enough, I did a benchmark based on a real project task.

    In said task, we had to write some config to RAM. Something like:

    coffee=hot
    sugar=none
    milk=breast
    mac=AA:BB:CC:DD:EE:FF

    Here's my benchmark programs (Yes, I know OP asked about printf(), not fprintf(). Try to capture the essence and by the way, OP's link points to fprintf() anyway.)

    C program:

    char coffee[10], sugar[10], milk[10];
    unsigned char mac[6];
    
    /* Initialize those things here. */
    
    FILE * f = fopen("a.txt", "wt");
    
    fprintf(f, "coffee=%s\nsugar=%s\nmilk=%s\nmac=%02X:%02X:%02X:%02X:%02X:%02X\n", coffee, sugar, milk, mac[0], mac[1],mac[2],mac[3],mac[4],mac[5]);
    
    fclose(f);
    

    C++ program:

    //Everything else is identical except:
    
    std::ofstream f("a.txt", std::ios::out);
    
    f << "coffee=" << coffee << "\n";
    f << "sugar=" << sugar << "\n";
    f << "milk=" << milk << "\n";
    f << "mac=" << (int)mac[0] << ":"
        << (int)mac[1] << ":"
        << (int)mac[2] << ":"
        << (int)mac[3] << ":"
        << (int)mac[4] << ":"
        << (int)mac[5] << endl;
    f.close();
    

    I did my best to polish them before I looped them both 100,000 times. Here are the results:

    C program:

    real    0m 8.01s
    user    0m 2.37s
    sys     0m 5.58s
    

    C++ program:

    real    0m 6.07s
    user    0m 3.18s
    sys     0m 2.84s
    

    Object file size:

    C   - 2,092 bytes
    C++ - 3,272 bytes
    

    Conclusion: On my very specific platform, with a very specific processor, running a very specific version of Linux kernel, to run a program which is compiled with a very specific version of GCC, in order to accomplish a very specific task, I would say the C++ approach is more suitable because it runs significantly faster and provide much better readability. On the other hand, C offers small footprint, in my opinion, means nearly nothing because program size is not of our concern.

    Remeber, YMMV.

提交回复
热议问题