#include "stdafx.h" #include <iostream> #include <windows.h> #include <WinBase.h> #include <WinNT.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { // DWORD start_time = GetTickCount(); // int k = 0; // for ( int i=0;i<1000000;++i) // { // ++k; // } // DWORD end_time=GetTickCount(); // // DWORD start_time1 = GetTickCount(); // int p = 0; // for ( int i=0;i<1000000;i++) // { // p++; // } // DWORD end_time1=GetTickCount(); // cout<<"The (++k) run time is:"<<(end_time-start_time)<<"ms!"<<endl;//输出运行时间 // cout<<"The (p++) run time is:"<<(end_time1-start_time1)<<"ms!"<<endl;//输出运行时间 LARGE_INTEGER litmp; LONGLONG QPart1, QPart2; LONGLONG QPart11, QPart12; double dfMinus, dfFreq, dfTim; double dfMinus1, dfTim1; int k = 0; QueryPerformanceFrequency(&litmp);//获取CPU时钟频率 dfFreq = (double)litmp.QuadPart; //------------------ QueryPerformanceCounter(&litmp); //获取开始计数值 QPart1 = litmp.QuadPart; k = 0; for ( int i=0;i<1000000;i++) { k++; } QueryPerformanceCounter(&litmp); //获取结束计数值 QPart2 = litmp.QuadPart; //------------------ QueryPerformanceCounter(&litmp); //获取开始计数值 QPart11 = litmp.QuadPart; k = 0; for ( int i=0;i<1000000;i++) { ++k; } QueryPerformanceCounter(&litmp); //获取结束计数值 QPart12 = litmp.QuadPart; dfMinus = (double)(QPart2-QPart1); dfTim = dfMinus/dfFreq; dfMinus1 = (double)(QPart12-QPart11); dfTim1 = dfMinus1/dfFreq; cout<<"The (k++) run time is:"<< dfTim <<"ms!"<<endl;//输出运行时间 cout<<"The (++k) run time is:"<< dfTim1 <<"ms!"<<endl;//输出运行时间 while (1) { if ( getchar() == 'a') { return 0; //只有输入A才会返回、退出 } } return 0; }
---------------------------------------------------------------------------------------------------------------
#ifndef COUNTTIME1000 #define COUNTTIME1000 //统计事件的类,用于多个线程当中会有风险 class CCountTime { public: //构造函数 CCountTime(); //析构函数,虚函数 virtual ~CCountTime(); //开始统计 void BeginCount(); //结束统计,返回结果,毫秒,重新开始计时 double EndCount(BOOL b_ReCount=FALSE); //时间统计参数 private: //64位整数 LARGE_INTEGER litmp; //时钟频率 double dfFreq; //用于获取两个时刻点的时间差,起始计时 LONGLONG QPart1; //用于获取两个时刻点的时间差,终止计时 LONGLONG QPart2; //返回的计时结果,单位微秒 double dfMinus; //返回的计时结果,单位毫秒 double dfTime; }; #endif
#include "stdafx.h" #include "CountTime.h" CCountTime::CCountTime() { //获得计时器的时钟频率 QueryPerformanceFrequency(&litmp); //时钟频率 dfFreq = (double)litmp.QuadPart; //开始计时 BeginCount(); } CCountTime::~CCountTime() { //不需要手动释放 } void CCountTime::BeginCount() { //获取高精度计时器的值 QueryPerformanceCounter(&litmp); //开始计时 QPart1 = litmp.QuadPart; } double CCountTime::EndCount(BOOL b_ReCount) { //获取高精度计时器的值 QueryPerformanceCounter(&litmp); //终止计时 QPart2 = litmp.QuadPart; //计算计数器值 dfMinus = (double)(QPart2 - QPart1); //获得对应时间, dfTime = dfMinus / dfFreq; //传入TRUE则重新计时 if (b_ReCount) { //开始计时 QPart1 = litmp.QuadPart; } //返回时间,单位毫秒 return dfTime*1000; }