! Microsecond-Level Timers
ExactTimer.h
#pragma once #include <math.h> BOOL readdwordkey in hkey hrootkey in lpctstr lpsubkey in lpctstr lpkey, out dword & dwvalue) { HKEY HK; if (error_success!=regopenkey(hrootkey, lpsubkey,&HK)) return FALSE; DWORD dwtype=REG_DWORD,dwlength=sizeof (DWORD); if (error_success!=RegQueryValueEx(HK,Lpkey,NULL,&dwtype,(Lpbyte) &dwvalue,&dwlength))return FALSE ;
RegCloseKey(HK); if (dwtype!=REG_DWORD) return FALSE;
return TRUE; }class Cexacttimer { Public: /** * constructor: Gets theCPUThe main frequency, accurate toMHz */ cexacttimer() {} ~cexacttimer(void) {} /** * get the elapsed time, US */ Double gettimespanmicrosecond() { DWORD dwcpufrequency=0; if (! readdwordkey ( hkey_local_machine Span style= ""color: "red& #34; > _t ( "hardware\\description\\system\\centralprocessor\ " _t ( dwcpufrequency return -1; return (_endtime-_starttime)/(dwcpufrequency *1.0); } /** * Stop Timing */ void Stop() { _endtime=getcyclecount(); } /** * Start Timing */ void Start() { _starttime=getcyclecount(); }Private: unsigned __int64 _starttime; unsigned __int64 _endtime; Double _nfrequencymhz; inline unsigned __int64 getcyclecount() { //rdtsc-read time-stamp Counter //Since the bootCPUnumber of clock cycles experienced __asm { _emit 0x0F; _emit 0x31; } }};
How to use:
Cexacttimer TimeSpan ;
TimeSpan . Start ();
int i=100000; while(---i); TimeSpan. Stop (); TRACE("%1.6fus\n",TimeSpan. Gettimespanmicrosecond ());
RDTSC instruction to achieve microsecond-level timers