cout or printf which of the two has a faster execution speed C++?

后端 未结 15 2864
旧时难觅i
旧时难觅i 2020-11-27 07:04

I have been coding in C++ for a long time. I always wondered which has a faster execution speed printf or cout?

Situation: I am designing a

15条回答
  •  盖世英雄少女心
    2020-11-27 07:38

    Why don't you do an experiment? On average for me, printing the string helloperson;\n using printf takes, on average, 2 clock ticks, while cout using endl takes a huge amount of time - 1248996720685 clock ticks. Using cout with "\n" as the newline takes only 41981 clock ticks. The short URL for my code is below:

    cpp.sh/94qoj

    link may have expired.

    To answer your question, printf is faster.

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    int main()
    {
      clock_t one;
      clock_t two;
      clock_t averagePrintf;
      clock_t averageCout;
      clock_t averagedumbHybrid;
      for (int j = 0; j < 100; j++) {
        one = clock();
        for (int d = 0; d < 20; d++) {
          printf("helloperson;");
          printf("\n");
        }
        two = clock();
        averagePrintf += two-one;
    
        one = clock();
        for (int d = 0; d < 20; d++) {
          cout << "helloperson;";
          cout << endl;
        }
        two = clock();
        averageCout += two-one;
    
        one = clock();
        for (int d = 0; d < 20; d++) {
          cout << "helloperson;";
          cout << "\n";
        }
        two = clock();
        averagedumbHybrid += two-one;
      }
      averagePrintf /= 100;
      averageCout /= 100;
      averagedumbHybrid /= 100;
      cout << "printf took " << averagePrintf << endl;
      cout << "cout took " << averageCout << endl;
      cout << "hybrid took " << averagedumbHybrid << endl;
    }
    

    Yes, I did use the word dumb. I first made it for myself, thinking that the results were crazy, so I searched it up, which ended up with me posting my code.

    Hope it helps, Ndrewffght

提交回复
热议问题