溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++如何實現(xiàn)統(tǒng)計代碼運行時間計時器的簡

發(fā)布時間:2021-04-14 11:11:33 來源:億速云 閱讀:331 作者:小新 欄目:編程語言

這篇文章將為大家詳細講解有關(guān)C++如何實現(xiàn)統(tǒng)計代碼運行時間計時器的簡,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

 C++實現(xiàn)統(tǒng)計代碼運行時間計時器的簡單實例

一、前言

         這里記下從網(wǎng)上找到的一些自己比較常用的C++計時代碼

二、Linux下精確至毫秒

#include <sys/time.h> 
#include <iostream> 
#include <time.h> 
double get_wall_time() 
{ 
  struct timeval time ; 
  if (gettimeofday(&time,NULL)){ 
    return 0; 
  } 
  return (double)time.tv_sec + (double)time.tv_usec * .000001; 
} 
 
int main() 
{ 
  unsigned int t = 0; 
  double start_time = get_wall_time() 
  while(t++<10e+6); 
  double end_time = get_wall_time() 
  std::cout<<"循環(huán)耗時為:"<<end_time-start_time<<"ms"; 
  return 0; 
}

三、Windows下精確至毫秒

#include <windows.h> 
#include <iostream> 
 
int main() 
{ 
  DWORD start, stop; 
  unsigned int t = 0; 
  start = GetTickCount(); 
  while (t++ < 10e+6); 
  stop = GetTickCount(); 
  printf("time: %lld ms\n", stop - start); 
  return 0; 
}

試驗中,發(fā)現(xiàn)貌似getTickCount函數(shù)會有10幾毫秒的誤差,囧。。。

四、Windows下精確至微秒

//MyTimer.h// 
#ifndef __MyTimer_H__  
#define __MyTimer_H__  
#include <windows.h>  
 
class MyTimer 
{ 
private: 
  int _freq; 
  LARGE_INTEGER _begin; 
  LARGE_INTEGER _end; 
 
public: 
  long costTime;      // 花費的時間(精確到微秒)  
 
public: 
  MyTimer() 
  { 
    LARGE_INTEGER tmp; 
    QueryPerformanceFrequency(&tmp);//QueryPerformanceFrequency()作用:返回硬件支持的高精度計數(shù)器的頻率。  
 
    _freq = tmp.QuadPart; 
    costTime = 0; 
  } 
 
  void Start()      // 開始計時  
  { 
    QueryPerformanceCounter(&_begin);//獲得初始值  
  } 
 
  void End()        // 結(jié)束計時  
  { 
    QueryPerformanceCounter(&_end);//獲得終止值  
    costTime = (long)((_end.QuadPart - _begin.QuadPart) * 1000000 / _freq); 
  } 
 
  void Reset()      // 計時清0  
  { 
    costTime = 0; 
  } 
}; 
#endif  
 
//main.cpp 
#include "MyTimer.h" 
#include <iostream> 
 
 
int main() 
{ 
  MyTimer timer; 
  unsigned int t = 0;  
  timer.Start(); 
  while (t++ < 10e+5); 
  timer.End();  
  std::cout << "耗時為:" << timer.costTime << "us"; 
  return 0 ; 
}

關(guān)于“C++如何實現(xiàn)統(tǒng)計代碼運行時間計時器的簡”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI