Click here to Skip to main content
6,305,776 members and growing! (15,052 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » Algorithms     Intermediate License: The Microsoft Public License (Ms-PL)

A C++ class for more precise time interval measurement

By George Anescu

A C++ class capable to measure time intervals in microseconds under Windows OS
VC6Win2K, Dev
Posted:11 Oct 2001
Updated:17 Oct 2001
Views:114,398
Bookmarked:41 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
35 votes for this article.
Popularity: 6.51 Rating: 4.21 out of 5
1 vote, 3.7%
1
2 votes, 7.4%
2
2 votes, 7.4%
3
6 votes, 22.2%
4
16 votes, 59.3%
5

Introduction

This timer class is capable to measure time intervals in microseconds under Windows OS. It is using the less known Windows API functions QueryPerformanceFrequency() and QueryPerformanceCounter() for getting the frequency and respectively the counts of the high-resolution performance counter. For systems where such a high-resolution performance counter is not available, the more known API function GetTickCounts() is used instead, but with a performance penalty on the timer's precision. The reliability of the timer is depending anyway on the system's hardware performance, i.e. the accuracy is increased for systems with higher processor frequency. The class is also demonstrating some useful tips about using the __int64 integers in VC++.

Implementation

Here I present only the public user interface of the CPreciseTimer class, the implementation details being in the demo project source files:

class CPreciseTimer
{
public:
    CPreciseTimer();
    bool SupportsHighResCounter();
    void StartTimer();
    void StopTimer();
    __int64 GetTime();
};
  • The constructor CPreciseTimer() at the first class's instance construction is also determining if the high-resolution performance counter is available, and in the favorable case is initializing the frequency member variable. Subsequent constructions are not repeating this computation block.

  • The function SupportsHighResCounter() is returning true only if the high-resolution performance counter is available. It is giving to the user a clue about the accuracy of the timer.

  • The function StartTimer(), as the name says, is starting the timer.

  • The function StopTimer() is stopping the timer, also keeping the elapsed time since the timer was started.

  • The function GetTime() in case the timer is in the running state is returning the time interval since the timer was started. If the timer is in the stopped state then it is returning the time difference between the last stop call and the last start call. The returned value is in microseconds, but it cannot be trusted if the high-resolution performance counter is not available, case for which the accuracy cannot be in fact higher than the order of milliseconds.

How to use it

The following code snippet is showing a simple use example:

CPreciseTimer oPreciseTimer;
cout << "Starting!" << endl;
oPreciseTimer.StartTimer();
::Sleep(5000);
cout << "Ending!" << endl;
oPreciseTimer.StopTimer();
__int64 i64Diff = oPreciseTimer.GetTime();
cout << "Diff=" << Int64ToString(i64Diff) << endl;
return 0;

I am using my own function Int64ToString() for displaying __int64 numbers. I also give this function for free use below:

string Int64ToString(__int64 const& ri64, int iRadix=10)
{
    bool bNeg = (ri64 < 0);
    __int64 i64 = ri64;
    string ostrRes;
    bool bSpecial = false;
    if(true == bNeg)
    {
        i64 = -i64;
        if(i64 < 0)
        // Special case number -9223372036854775808 or 

        // 0x8000000000000000

        bSpecial = true;
        ostrRes.append(1, '-');
    }
    int iR;
    do
    {
        iR = i64 % iRadix;
        if(true == bSpecial)
            iR = -iR;
        if(iR < 10)
            ostrRes.append(1, '0' + iR);
        else
            ostrRes.append(1, 'A' + iR - 10);
        i64 /= iRadix;
    }
    while(i64 != 0);
    //Reverse the string

    string::iterator it = ostrRes.begin();
    if(bNeg)
        it++;
    reverse(it, ostrRes.end());
    return ostrRes;
}

It is capable to display __int64 values in any radix base (the default radix base being 10). __int64 values can also be displayed using the printf() function as in the following code snippet:

__int64 i64 = 0x7fffffffffffffff;
printf("Decimal Value = %I64d\n", i64);
printf("Hexa Value = %I64x\n", i64);

You can also use in MFC applications the Format() function of CString:

CString str;
str.Format("%I64d", 4294967307);

or a stdlib function _i64toa() which is similar to itoa():

__int64 i64 = 4294967307;
char szBuff[20];
_i64toa(i64, szBuff, 10);

Conclusion

The project attached to this article contains the source code of the presented CPreciseTimer class and test code. I am interested in any opinions and new ideas about this implementation.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

About the Author

George Anescu


Member

Occupation: Web Developer
Location: Romania Romania

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 12 of 12 (Total in Forum: 12) (Refresh)FirstPrevNext
Generalaccuracy of project Pinmemberreyahy1:00 9 Aug '06  
GeneralUpdateElapsed PinmemberMasterGohan13:31 3 May '06  
GeneralC++ MFC timer help... Pinmemberyihaa17:21 27 Aug '04  
GeneralAsk about Tree PinmemberMinhHai22:13 1 Jul '03  
GeneralRe: Ask about Tree PinmemberPROFABULOUS16:43 22 Apr '05  
GeneralCheck out CPerfTimer PinmemberDean Wyant6:05 22 Oct '01  
GeneralRe: Check out CPerfTimer PinsussKimon Hoffmann13:22 12 Aug '02  
GeneralConverting I64 to string PinmemberAnonymous23:33 14 Oct '01  
GeneralRe: Converting I64 to string PinmemberGeorge Anescu3:51 15 Oct '01  
GeneralConverting int64 to string PinmemberBilby22:53 14 Oct '01  
GeneralRe: Converting int64 to string PinmemberGeorge Anescu3:51 15 Oct '01  
GeneralRe: Converting int64 to string Pinmembernjeccles5:09 22 Mar '02  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Oct 2001
Editor: Nishant Sivakumar
Copyright 2001 by George Anescu
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project