Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Precise duration measurement

0.00/5 (No votes)
27 Dec 1999 1  
A simple class that provides high precision timing.
  • Download demo project - 5 Kb
  • Download source files - 1 Kb
  • Here is a simple class used to measure the duration of functions or code parts (from some microseconds to milliseconds) using the Windows high precision timer.

    This class is very easy to use. The following code measure the duration of the Foo function:

        CDuration timer;
    
        timer.Start();
        Foo();
        timer.Stop();
    
        cout << "Foo duration: " << timer.GetDuration()/1000.0 << " milliseconds" << endl;
    

    The GetDuration() method returns the number of microseconds between calls to Start() and Stop(). This value depends on the precision of the internal timer. In a multitasking operating system like Windows, it is difficult to make very accurate duration measurement. Thus, measurement less than a few milliseconds will be correct, but longer measurement could have a difference of a tenth of a millisecond or more because of tasks switching.

    The constructor implements a calibration procedure so the following code will return 0 milliseconds:

        CDuration dur;
    
        dur.Start();
        dur.Stop();
    
        cout << "Zero duration: " << dur.GetDuration()/1000.0 << " milliseconds" << endl;
    

    If you really need no task switching during a long time, you could increment the process and thread priority in the Start() method and decrement it in Stop() .

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here