In C + +, it is often necessary to count performance information by timing, and to analyze performance bottlenecks through statistical time-consuming information, which can often be sufficient for millisecond-level time statistics, but in the case of least bit performance hotspots, millisecond-level statistics are not enough, Requires at least a microsecond level of statistical information, even to the CPU's instruction cycle level. Let's focus on the timing statistics for the millisecond level.
Least bit--microsecond timing ideas
On the Windows platform, the two Windows APIs are used to count the time-consuming information of the microsecond level:
BOOL WINAPI queryperformancefrequency ( _out_ *lpfrequency); BOOL WINAPI QueryPerformanceCounter ( _out_ *lpperformancecount);
QueryPerformanceFrequency is used to get the frequency of performance counts, how many times per second,
QueryPerformanceCounter is used to get the value of the current performance count.
With these two APIs, we'll be able to count time-consuming ideas like this:
So how to get the final time-consuming, I believe it is not difficult to answer, the formula is as follows:
seconds time Elapsed = (End performance Count value-start performance count value)/1000000 /performance Count frequency
Microsecond Timing Implementation
Large_integer Freq_; QueryPerformanceFrequency (&freq_); Large_integer Begin_time; Large_integer End_time; QueryPerformanceCounter (&begin_time); Sleep (+); QueryPerformanceCounter (&end_time); Double 1000000.0 /freq_. QuadPart;
Implementation of package Microsecond timing
Although the above has been achieved microsecond precision timing, but because every time the API is called to define variables, etc., there will certainly be a lot of duplication or similar code, in order to avoid this situation, the implementation is encapsulated, as follows:
classstop_watch{ Public: Stop_watch (): Elapsed_ (0) {QueryPerformanceFrequency (&freq_); } ~Stop_watch () {} Public: voidstart () {QueryPerformanceCounter (&begin_time_); } voidStop () {Large_integer end_time; QueryPerformanceCounter (&end_time); Elapsed_+ = (end_time. Quadpart-begin_time_. QuadPart) *1000000/freq_. QuadPart; } voidRestart () {elapsed_=0; Start (); } //microseconds Doubleelapsed () {returnstatic_cast<Double>(Elapsed_); } //milliseconds DoubleElapsed_ms () {returnElapsed_/1000.0; } //seconds DoubleElapsed_second () {returnElapsed_/1000000.0; }Private: Large_integer freq_; Large_integer Begin_time_; Long Longelapsed_;};
So, how to use this encapsulated class, take a look at the invocation example:
Stop_watch Watch;watch.start (); Sleep (" ns" << Endl;
See if the call is more convenient, it is not a bit familiar feeling, yes, yes, you guessed right ...
Resources
QueryPerformanceFrequency
QueryPerformanceCounter
C + + High performance counters-microsecond time statistics