Inaccurate timing of clock in C++?

 #include<iostream>
#include<ctime>
using namespace std;
int main()
 {
    
    
     clock_t startTime1,endTime1;
     startTime1 = clock();//计时开始
     long int sum1 = 0;
     for (int i = 0; i < 1000000; i++)
     {
    
    
         sum1 += i;
         cout << "sum: " << sum1 << endl;
     }
     endTime1 = clock();//计时结束
     cout << "The run time is: " <<(double)(endTime1 - startTime1) / CLOCKS_PER_SEC << "s" << endl;
    
     clock_t startTime2,endTime2;
     startTime2 = clock();//计时开始
     long int sum2 = 0;
     for (int i = 0; i < 1000000; i++)
     {
    
    
         sum2 += i;
         //cout << "sum: " << sum << endl;
     }
     endTime2 = clock();//计时结束
     cout << "The run time is: " <<(double)(endTime2 - startTime2) / CLOCKS_PER_SEC << "s" << endl;
     return 0;
}

In fact, the clock timing of Linux C++ is accurate, but it hasn't been displayed in the terminal yet, which leads you to think that the program has not been executed yet, and the program has been executed long ago, but the terminal hasn't finished displaying yet.

Guess you like

Origin blog.csdn.net/weixin_40437821/article/details/113611537