這篇文章將為大家詳細講解有關C++如何實現統計代碼運行時間計時器的簡,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
C++實現統計代碼運行時間計時器的簡單實例
一、前言
這里記下從網上找到的一些自己比較常用的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<<"循環耗時為:"<<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;
}試驗中,發現貌似getTickCount函數會有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()作用:返回硬件支持的高精度計數器的頻率。
_freq = tmp.QuadPart;
costTime = 0;
}
void Start() // 開始計時
{
QueryPerformanceCounter(&_begin);//獲得初始值
}
void End() // 結束計時
{
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 ;
}關于“C++如何實現統計代碼運行時間計時器的簡”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。