printf more than 5 times faster than std::cout?

后端 未结 6 893
遇见更好的自我
遇见更好的自我 2020-12-09 10:44
#include 
#include 
#include 
#include 

int main(int argc, char* argv[])
{
    std::clock_t start;
    dou         


        
6条回答
  •  半阙折子戏
    2020-12-09 11:01

    I tried this test on my laptop, running Windows 10, WSL Ubuntu, CLion 2018, GCC. No optimization:

    #include 
    #include 
    #include 
    #include 
    
    int main(int argc, char *argv[]) {
        std::ios_base::sync_with_stdio(false);
        std::cin.tie(nullptr);
        std::clock_t start;
        double duration1, duration2;
    
        std::cout << "Starting std::cout test.\n";
        start = std::clock();
    
        for (int i = 0; i < 100000; i++) {
            std::cout << "Hello, World! (" << i << ")" << std::endl;
        }
    
        duration1 = (std::clock() - start) / (double) CLOCKS_PER_SEC;
    
        std::cout << "Starting std::printf test.\n";
        start = std::clock();
    
        for (int i = 0; i < 100000; i++) {
            std::printf("Hello, World! (%i)\n", i);
            std::fflush(stdout);
        }
    
        duration2 = (std::clock() - start) / (double) CLOCKS_PER_SEC;
    
        std::cout << "Time taken: cout " << duration1 << std::endl;
        std::cout << "Time taken Printf: " << duration2 << std::endl;
    
        return 0;
    }
    

    Results:

    Test1: Cout: 2.25, Printf: 2.45312  (Cout run first)
    Test2: Cout: 2.42188, Printf: 2.07812 (Printf Run first)
    Test3: Cout: 2.26562, Printf: 2.25 (Cout run first)
    Test4: Cout 2.46875, Printf: 2.57812 (Printf run first)
    

    TL;DR: Using std::ios_base::sync_with_stdio(false) and std::cin.tie(nullptr) brings both functions to almost the same stand.

提交回复
热议问题