Click here to Skip to main content
15,438,095 members
Articles / Programming Languages / C#
Posted 25 Jul 2002

Tagged as


135 bookmarked

High-Performance Timer in C#

Rate me:
Please Sign up or sign in to vote.
4.81/5 (54 votes)
29 Jul 2002CPOL2 min read
A C# class to provide exact time measurement in your applications
In this article, you will see a C# class which can provide exact time measurement in applications.

UML Image


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 achieves 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 have 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
        private static extern bool QueryPerformanceCounter(
            out long lpPerformanceCount);

        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()
            // let's do the waiting threads there work

            QueryPerformanceCounter(out startTime);

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

        // Returns the duration of the timer (in seconds)
        public double Duration
                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


  • 26th July, 2002 - Posted (first version)
  • 29th August, 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.


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

Written By
Austria Austria
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

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 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
eyedia4-Feb-11 8:20
Membereyedia4-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 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 
GeneralGarbage Colection in .NET Pin
Nguyen Thanh Luc22-May-08 17:22
MemberNguyen Thanh Luc22-May-08 17:22 
GeneralSystem.Diagnostics.Stopwatch class PinPopular
Mach0055-Apr-07 23:49
MemberMach0055-Apr-07 23:49 
GeneralSome Corrections Pin
Steven James Gray27-Mar-07 21:43
MemberSteven James Gray27-Mar-07 21:43 
GeneralGotcha's to watch out for PinPopular
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
MemberAnonymous29-Sep-05 8:55 

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

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