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

創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供鄂溫克網(wǎng)站建設、鄂溫克做網(wǎng)站、鄂溫克網(wǎng)站設計、鄂溫克網(wǎng)站制作等企業(yè)網(wǎng)站建設、網(wǎng)頁設計與制作、鄂溫克企業(yè)網(wǎng)站模板建站服務,十多年鄂溫克做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎ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 ;
}關于“C++如何實現(xiàn)統(tǒng)計代碼運行時間計時器的簡”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
本文名稱:C++如何實現(xiàn)統(tǒng)計代碼運行時間計時器的簡
瀏覽地址:http://chinadenli.net/article22/iigecc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、軟件開發(fā)、品牌網(wǎng)站設計、品牌網(wǎng)站建設、商城網(wǎng)站、網(wǎng)站導航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)