计算运行时间

  • LINK:https://zhuanlan.zhihu.com/p/54665895

    1) clock()

    返回从 开启这个程序进程 到 程序中调用clock()函数 时之间的CPU时钟计时单元(clock tick)数(挂钟时间),返回单位是毫秒 ```cpp // time.h

clock_t start,end;  start = clock();    / code / end = clock();
cout<<”time = “<<double(end-start)/CLOCKS_PER_SEC<<”s”<<endl;

  1. <a name="h8Rr0"></a>
  2. #### 2)GetTickCount() // windows api
  3. 返回从操作系统启动到现在所经过的毫秒数(ms), 精确度在16ms左右,最精确也不会精确过10ms
  4. ```cpp
  5. #include <windows.h>   //引入头文件
  6. int main()
  7. {
  8. DWORD t1,t2;
  9. t1 = GetTickCount();
  10. fun() //需计时的函数
  11. t2 = GetTickCount();
  12. cout<<"time = "<<((t2-t1)*1.0/1000)<<endl; //输出时间(单位:s)
  13. }

3) QueryPerformanceCounter() // windows api

  1. #include <windows.h>   //引入头文件
  2. int main()
  3. {
  4. LARGE_INTEGER t1,t2,tc;
  5. QueryPerformanceFrequency(&tc);
  6. QueryPerformanceCounter(&t1);
  7. fun() //需计时的函数
  8. QueryPerformanceCounter(&t2);
  9. time=(double)(t2.QuadPart-t1.QuadPart)/(double)tc.QuadPart;
  10. cout<<"time = "<<time<<endl; //输出时间(单位:s)
  11. }

4) gettimeofday() // linux

  1. //timeval结构定义为:
  2. struct timeval{
  3. long tv_sec; /*秒*/
  4. long tv_usec; /*微秒*/
  5. };
  6. //timezone 结构定义为:
  7. struct timezone{
  8. int tz_minuteswest; /*和Greenwich 时间差了多少分钟*/
  9. int tz_dsttime; /*日光节约时间的状态*/
  10. };
  1. #include <sys/time.h>   //引入头文件
  2. int main()
  3. {
  4. struct timeval t1,t2;
  5. double timeuse;
  6. gettimeofday(&t1,NULL);
  7. fun();
  8. gettimeofday(&t2,NULL);
  9. timeuse = (t2.tv_sec - t1.tv_sec) + (double)(t2.tv_usec - t1.tv_usec)/1000000.0;
  10. cout<<"time = "<<timeuse<<endl; //输出时间(单位:s)
  11. }