RDTSC instruction to achieve microsecond-level timers

Source: Internet
Author: User

! 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.