C++實現(xiàn)統(tǒng)計代碼運行時間計時器的簡單實例
更新時間:2017年07月08日 11:21:25 投稿:lqh
這篇文章主要介紹了 C++實現(xiàn)統(tǒng)計代碼運行時間計時器的簡單實例的相關(guān)資料,需要的朋友可以參考下
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)柏林噪聲算法(Perlin?Noise)
Perlin噪聲(Perlin?noise,又稱為柏林噪聲)指由Ken?Perlin發(fā)明的自然噪聲生成算法,具有在函數(shù)上的連續(xù)性,并可在多次調(diào)用時給出一致的數(shù)值。本文將用C++實現(xiàn)柏林噪聲算法,感興趣的可以了解一下2023-03-03深入理解數(shù)組指針與指針數(shù)組的區(qū)別
本篇文章是對數(shù)組指針與指針數(shù)組的區(qū)別進行了詳細的分析介紹,需要的朋友參考下2013-05-05