C++ 程序耗时统计

在编程过程中经常需要统计一个代码段的耗时,本文主要记录 C++ 常用的耗时统计方式。

系统存储时间常见的两种方式为:

  1. 存储从1970年到现在经过多少时间
  2. 使用结构体分别存储当前时间的年月日时分秒

主要记录 time_tstruct time_valchrono 统计时间的相关函数使用方法:

  • time_t

    • 说明:存储了从1970年到现在经过了多少,所以使用time_t的精度也就是级别

    • 类型: time_t 实际上就是long int 类型

    • 函数:

      double difftime(time_t time1, time_t time2)
      
    • 示例:

      #include 
      #include 
      void test_time_t(){
      	time_t start_time, end_time;
      	time(&start_time);
      	...
      	time(&end_time);
      	double cost_time = difftime(end_time, start_time);
      	std::cout << "run func cost " << cost_time << " seconds" << std::endl;
      }
      
  • struct timeval

    • 说明:存储了从1970年到现在经过了多少微妙,所以使用timeval的精度也就是微妙级别

    • 类型:

      struct timeval{
          long tv_sec; /*秒*/
          long tv_usec; /*微秒*/
      };
      
    • 函数:

      int gettimeofday(struct timeval *tv, struct timezone *tz);
      
    • 注意:gettimeofdaylinux 系统函数

    • 示例

      #include 
      #include 
      #include 
      void test_timeval(){
      	struct timeval start_time;
          struct timeval end_time;
      	gettimeofday(&start_time, NULL);
      	...
      	gettimeofday(&end_time,NULL);
      	float cost_time = (end_time.tv_sec - start_time.tv_sec)*1000
                          + (end_time.tv_usec - start_time.tv_usec)/1000;
      	std::cout << "run func cost " << cost_time << " ms" << std::endl;
      }
      
  • chrono

    • 说明:chronoc++ 11中的时间库,提供计时,时钟等功能

    • 示例

    	  #include 
    	  using namespace std;
    	  using std::chrono::high_resolution_clock;
    	  using std::chrono::milliseconds;
    	  
    	  int test_chrono(){
    	  	high_resolution_clock::time_point start_time = high_resolution_clock::now();
    	  		...
    	  	high_resolution_clock::time_point end_time = high_resolution_clock::now();
    	  	milliseconds time_interval = std::chrono::duration_cast<milliseconds>(end_time - start_time);
    	  	cout << "run func cost " << time_interval.count() << " ms" endl;
    	  }
    

你可能感兴趣的:(C/C++,c++,开发语言)