這篇文章將為大家詳細(xì)講解有關(guān)C++如何實(shí)現(xiàn)統(tǒng)計(jì)代碼運(yùn)行時(shí)間計(jì)時(shí)器的簡(jiǎn),小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供鄂溫克網(wǎng)站建設(shè)、鄂溫克做網(wǎng)站、鄂溫克網(wǎng)站設(shè)計(jì)、鄂溫克網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、鄂溫克企業(yè)網(wǎng)站模板建站服務(wù),十多年鄂溫克做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
C++實(shí)現(xiàn)統(tǒng)計(jì)代碼運(yùn)行時(shí)間計(jì)時(shí)器的簡(jiǎn)單實(shí)例
一、前言
這里記下從網(wǎng)上找到的一些自己比較常用的C++計(jì)時(shí)代碼
二、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)耗時(shí)為:"<<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; }
試驗(yàn)中,發(fā)現(xiàn)貌似getTickCount函數(shù)會(huì)有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; // 花費(fèi)的時(shí)間(精確到微秒) public: MyTimer() { LARGE_INTEGER tmp; QueryPerformanceFrequency(&tmp);//QueryPerformanceFrequency()作用:返回硬件支持的高精度計(jì)數(shù)器的頻率。 _freq = tmp.QuadPart; costTime = 0; } void Start() // 開(kāi)始計(jì)時(shí) { QueryPerformanceCounter(&_begin);//獲得初始值 } void End() // 結(jié)束計(jì)時(shí) { QueryPerformanceCounter(&_end);//獲得終止值 costTime = (long)((_end.QuadPart - _begin.QuadPart) * 1000000 / _freq); } void Reset() // 計(jì)時(shí)清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 << "耗時(shí)為:" << timer.costTime << "us"; return 0 ; }
關(guān)于“C++如何實(shí)現(xiàn)統(tǒng)計(jì)代碼運(yùn)行時(shí)間計(jì)時(shí)器的簡(jiǎn)”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
本文名稱:C++如何實(shí)現(xiàn)統(tǒng)計(jì)代碼運(yùn)行時(shí)間計(jì)時(shí)器的簡(jiǎn)
瀏覽地址:http://vcdvsql.cn/article22/iigecc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、軟件開(kāi)發(fā)、品牌網(wǎng)站設(shè)計(jì)、品牌網(wǎng)站建設(shè)、商城網(wǎng)站、網(wǎng)站導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)