Easily measure elapsed time

前端 未结 26 2203
栀梦
栀梦 2020-11-22 04:13

I am trying to use time() to measure various points of my program.

What I don\'t understand is why the values in the before and after are the same? I understand thi

26条回答
  •  旧时难觅i
    2020-11-22 05:04

    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    using namespace std::chrono;
    
    void f1()
    {
      high_resolution_clock::time_point t1 = high_resolution_clock::now();
      high_resolution_clock::time_point t2 = high_resolution_clock::now();
      double dif = duration_cast( t2 - t1 ).count();
      printf ("Elasped time is %lf nanoseconds.\n", dif );
    }
    
    void f2()
    {
      timespec ts1,ts2;
      clock_gettime(CLOCK_REALTIME, &ts1);
      clock_gettime(CLOCK_REALTIME, &ts2);
      double dif = double( ts2.tv_nsec - ts1.tv_nsec );
      printf ("Elasped time is %lf nanoseconds.\n", dif );
    }
    
    void f3()
    {
      struct timeval t1,t0;
      gettimeofday(&t0, 0);
      gettimeofday(&t1, 0);
      double dif = double( (t1.tv_usec-t0.tv_usec)*1000);
      printf ("Elasped time is %lf nanoseconds.\n", dif );
    }
    void f4()
    {
      high_resolution_clock::time_point t1 , t2;
      double diff = 0;
      t1 = high_resolution_clock::now() ;
      for(int i = 1; i <= 10 ; i++)
      {
        t2 = high_resolution_clock::now() ;
        diff+= duration_cast( t2 - t1 ).count();
        t1 = t2;
      }
      printf ("high_resolution_clock:: Elasped time is %lf nanoseconds.\n", diff/10 );
    }
    
    void f5()
    {
      timespec ts1,ts2;
      double diff = 0;
      clock_gettime(CLOCK_REALTIME, &ts1);
      for(int i = 1; i <= 10 ; i++)
      {
        clock_gettime(CLOCK_REALTIME, &ts2);
        diff+= double( ts2.tv_nsec - ts1.tv_nsec );
        ts1 = ts2;
      }
      printf ("clock_gettime:: Elasped time is %lf nanoseconds.\n", diff/10 );
    }
    
    void f6()
    {
      struct timeval t1,t2;
      double diff = 0;
      gettimeofday(&t1, 0);
      for(int i = 1; i <= 10 ; i++)
      {
        gettimeofday(&t2, 0);
        diff+= double( (t2.tv_usec-t1.tv_usec)*1000);
        t1 = t2;
      }
      printf ("gettimeofday:: Elasped time is %lf nanoseconds.\n", diff/10 );
    }
    
    int main()
    {
      //  f1();
      //  f2();
      //  f3();
      f6();
      f4();
      f5();
      return 0;
    }
    

提交回复
热议问题