Click here to Skip to main content
11,500,106 members (61,260 online)
Click here to Skip to main content

High-Performance Timer in C#

, 29 Jul 2002 CPOL 95 4.1K 127
Rate this:
Please Sign up or sign in to vote.
A C# class to provide exact time measurement in your applications.

UML Image

Introduction

In some applications exact time measurement methods are very important. The often used Windows API method GetTickCount() retrieves the number of milliseconds that have elapsed since the system was started, but the GetTickCount() function only archieve resolutions of 1ms and on the other side they are very imprecise.

So, for exact time measurement we should find another method.

High resolution timing is supported in Win32 by the QueryPerformanceCounter() and QueryPerformanceFrequency() API methods. This timer functions has much better resolution than the "standard" millisecond-based timer calls, like the GetTickCount() method. On the other side there is also a little bit overhead when calling this "unmanaged" API methods from C#, but it's better than using the very imprecise GetTickCount() API function.

The first call, QueryPerformanceCounter(), queries the actual value of the high-resolution performance counter at any point. The second function, QueryPerformanceFrequency(), will return the number of counts per second that the high-resolution counter performs. To retrieve the elapsed time of a code section you have to get the actual value of the high-resolution performance counter immediately before and immediately after the section of code to be timed. The difference of these values would indicate the counts that elapsed while the code executed.

The elapsed time can be computed then, by dividing this difference by the number of counts per second that the high-resolution counter performs (the frequency of the high-resolution timer).

duration = (stop - start) / frequency

For more information about QueryPerformanceCounter and QueryPerformanceFrequency read the documentation on MSDN.

The Code

The following class implements the functionality of the QueryPerformanceCounter() and QueryPerformanceFrequency() API methods.

using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Win32
{
    internal class HiPerfTimer
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(
            out long lpPerformanceCount);

        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(
            out long lpFrequency);

        private long startTime, stopTime;
        private long freq;

        // Constructor
        public HiPerfTimer()
        {
            startTime = 0;
            stopTime  = 0;

            if (QueryPerformanceFrequency(out freq) == false)
            {
                // high-performance counter not supported
                throw new Win32Exception();
            }
        }

        // Start the timer
        public void Start()
        {
            // lets do the waiting threads there work
            Thread.Sleep(0);

            QueryPerformanceCounter(out startTime);
        }

        // Stop the timer
        public void Stop()
        {
            QueryPerformanceCounter(out stopTime);
        }

        // Returns the duration of the timer (in seconds)
        public double Duration
        {
            get
            {
                return (double)(stopTime - startTime) / (double) freq;
            }
        }
    }
}

This class is very simple to use. Just create an instance of HiPerfTimer, call Start() to start timing and call Stop() to stop timing. To retrieve the elapsed time, just call the Duration() function and you will get the elapsed time.

The following sample should explain that.

HiPerfTimer pt = new HiPerfTimer();     // create a new PerfTimer object
pt.Start();                             // start the timer
Console.WriteLine("Test\n");            // the code to be timed
pt.Stop();                              // stop the timer
Console.WriteLine("Duration: {0} sec\n", 
     pt.Duration); // print the duration of the timed code

The following image shows the output of this sample on my system.

Sample Output

History

  • 26.07.2002 - posted (first version)
  • 29.08.2002 - added some code for more robustness of the class

Bugs and comments

If you have any comments or find some bugs, I would love to hear about it and make it better.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Daniel Strigl

Austria Austria
No Biography provided

Comments and Discussions

 
QuestionIt's perfect ! it's a good start for me I think ... Pin
Kris-I23-Apr-14 22:09
memberKris-I23-Apr-14 22:09 
GeneralMy vote of 5 Pin
Besic Denis24-Apr-13 2:58
memberBesic Denis24-Apr-13 2:58 
SuggestionThis code is obsolete in .NET 2.0 and above [modified] Pin
Pavel Vladov17-Jul-12 22:18
memberPavel Vladov17-Jul-12 22:18 
GeneralRe: This code is obsolete in .NET 2.0 and above - NOT WRT Silverlight Pin
dwrogers7-Feb-14 14:44
memberdwrogers7-Feb-14 14:44 
GeneralMy vote of 1 Pin
hsnfrz25-May-12 0:51
memberhsnfrz25-May-12 0:51 
QuestionHelp ??????!!!!!!!! About the time calculated Pin
Yanbei20-Jan-12 7:01
memberYanbei20-Jan-12 7:01 
GeneralMy vote of 5 Pin
Big D4-Feb-11 8:20
memberBig D4-Feb-11 8:20 
GeneralMSDN remarks about using this High Performance Timer Pin
Member 399685330-Oct-10 23:51
memberMember 399685330-Oct-10 23:51 
GeneralRe: MSDN remarks about using this High Performance Timer Pin
Jay R. Wren17-May-11 5:45
memberJay R. Wren17-May-11 5:45 
GeneralMy vote of 5 Pin
Jibrohni12-Jul-10 1:35
memberJibrohni12-Jul-10 1:35 
Questiontimer code in c# to call in a method which id dynamic..ie not static?? Pin
merryjoy00012-Feb-09 0:38
membermerryjoy00012-Feb-09 0:38 
QuestionIs it possible to use this and trigger an Event? Pin
m.otte28-Jan-09 4:00
memberm.otte28-Jan-09 4:00 
AnswerRe: Is it possible to use this and trigger an Event? Pin
NortuRE21-Aug-10 22:05
memberNortuRE21-Aug-10 22:05 
Generalnice class Pin
El Corazon7-Sep-08 8:40
memberEl Corazon7-Sep-08 8:40 
you might add a frame timer. Depending on the business, it is called a continuous timer or sample timer, or a time marker. The concept is basically that your end time from one event is the start of another. Although you can add multiple start/stop and duration calls, the extra start command has very small time lost from the stop to the restart.

In continuous mode the stop time is moved to the start after evaluating a marked time duration. Or alternately the previous stop-time is moved to the start prior to calling the stop time. Very handy in evaluating time on continuous events.

I added my own, but thought you might consider it. Thanks for the article!

_________________________
Asu no koto o ieba, tenjo de nezumi ga warau.
Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)
John Andrew Holmes "It is well to remember that the entire universe, with one trifling exception, is composed of others."

GeneralGarbage Colection in .NET Pin
Nguyen Thanh Luc22-May-08 17:22
memberNguyen Thanh Luc22-May-08 17:22 
GeneralSystem.Diagnostics.Stopwatch class Pin
Mach0055-Apr-07 23:49
memberMach0055-Apr-07 23:49 
GeneralSome Corrections Pin
CobaltSoftware27-Mar-07 21:43
memberCobaltSoftware27-Mar-07 21:43 
GeneralGotcha's to watch out for Pin
Kodiak737-Feb-07 22:20
memberKodiak737-Feb-07 22:20 
GeneralMeasurement Pin
Gary Kirkham7-May-06 2:00
memberGary Kirkham7-May-06 2:00 
GeneralRe: Measurement Pin
SOUL_REAPER26-Dec-07 4:14
memberSOUL_REAPER26-Dec-07 4:14 
GeneralSeems pretty consistent to me! Pin
sklett11-Apr-06 13:49
membersklett11-Apr-06 13:49 
GeneralA clarification of the Sleep(0) call in Start() Pin
DrGary833-Jan-06 9:32
memberDrGary833-Jan-06 9:32 
GeneralStopwatch class from .net 2.0 framework ported .net 1.1 Pin
Paul Welter30-Jun-05 19:50
memberPaul Welter30-Jun-05 19:50 
GeneralErrors using code Pin
perkash7-Apr-05 0:14
memberperkash7-Apr-05 0:14 
GeneralRe: Errors using code Pin
Anonymous29-Sep-05 8:55
sussAnonymous29-Sep-05 8:55 
GeneralRe: Errors using code Pin
Ri Qen-Sin13-Sep-07 4:41
memberRi Qen-Sin13-Sep-07 4:41 
GeneralParameters should be ref long Pin
axelriet21-Feb-05 16:50
memberaxelriet21-Feb-05 16:50 
GeneralRe: Parameters should be ref long Pin
Anonymous18-Mar-05 3:39
sussAnonymous18-Mar-05 3:39 
GeneralRe: Parameters should be ref long Pin
axelriet18-Mar-05 7:13
memberaxelriet18-Mar-05 7:13 
QuestionWhat is this returning? Pin
jobobner6-Jan-05 4:52
memberjobobner6-Jan-05 4:52 
AnswerRe: What is this returning? Pin
Sander van Driel17-Jan-05 7:26
memberSander van Driel17-Jan-05 7:26 
GeneralRe: What is this returning? Pin
Big D7-Feb-11 4:15
memberBig D7-Feb-11 4:15 
GeneralInaccurate Timer duration Pin
Joseph McGowan3-Dec-04 4:10
memberJoseph McGowan3-Dec-04 4:10 
GeneralRe: Inaccurate Timer duration Pin
Anonymous12-Jan-05 8:28
sussAnonymous12-Jan-05 8:28 
GeneralRe: Inaccurate Timer duration Pin
Liu Junfeng5-Apr-05 3:04
memberLiu Junfeng5-Apr-05 3:04 
GeneralRe: Inaccurate Timer duration Pin
SuperMegaProg8-Mar-06 7:45
memberSuperMegaProg8-Mar-06 7:45 
GeneralRe: Inaccurate Timer duration Pin
Brian Clifton11-May-07 11:04
memberBrian Clifton11-May-07 11:04 
GeneralRe: Inaccurate Timer duration Pin
mbelshe13-Aug-07 11:05
membermbelshe13-Aug-07 11:05 
GeneralRe: Inaccurate Timer duration Pin
Brian Clifton26-Sep-07 10:36
memberBrian Clifton26-Sep-07 10:36 
GeneralOptimization Pin
Anonymous28-Sep-04 6:16
sussAnonymous28-Sep-04 6:16 
GeneralRe: Optimization Pin
Anonymous28-Sep-04 6:18
sussAnonymous28-Sep-04 6:18 
GeneralAdding a new propery for split timing Pin
jimboc426-Apr-04 6:01
memberjimboc426-Apr-04 6:01 
GeneralUsing this in a GPL application Pin
Bjornar Henden18-Sep-03 11:24
memberBjornar Henden18-Sep-03 11:24 
GeneralRe: Using this in a GPL application Pin
Daniel S.11-Oct-03 2:34
memberDaniel S.11-Oct-03 2:34 
GeneralRe: Using this in a GPL application Pin
Bjornar Henden11-Oct-03 2:52
memberBjornar Henden11-Oct-03 2:52 
GeneralEXCELLENT Pin
eggie527-Jul-03 20:51
membereggie527-Jul-03 20:51 
GeneralRe: EXCELLENT Pin
Daniel S.16-Sep-03 21:52
memberDaniel S.16-Sep-03 21:52 
GeneralRe: EXCELLENT Pin
Jaime Olivares29-Oct-05 8:36
memberJaime Olivares29-Oct-05 8:36 
GeneralFor Windows CE.NET Pin
Frank Dzaebel25-Jul-03 4:23
memberFrank Dzaebel25-Jul-03 4:23 
GeneralRe: For Windows CE.NET Pin
Daniel S.25-Jul-03 4:54
memberDaniel S.25-Jul-03 4:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 30 Jul 2002
Article Copyright 2002 by Daniel Strigl
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid