Click here to Skip to main content
11,412,578 members (71,937 online)
Click here to Skip to main content

High-Performance Timer in C#

, 29 Jul 2002 CPOL
Rate this:
Please Sign up or sign in to vote.
A C# class to provide exact time measurement in your 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 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
        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()
            // lets 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


  • 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.


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


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-I at 23-Apr-14 23:09
memberKris-I23-Apr-14 23:09 
GeneralMy vote of 5 Pin
Besic Denis at 24-Apr-13 3:58
memberBesic Denis24-Apr-13 3:58 
SuggestionThis code is obsolete in .NET 2.0 and above [modified] Pin
Pavel Vladov at 17-Jul-12 23:18
memberPavel Vladov17-Jul-12 23:18 
GeneralRe: This code is obsolete in .NET 2.0 and above - NOT WRT Silverlight Pin
dwrogers at 7-Feb-14 15:44
memberdwrogers7-Feb-14 15:44 
GeneralMy vote of 1 Pin
hsnfrz at 25-May-12 1:51
memberhsnfrz25-May-12 1:51 
QuestionHelp ??????!!!!!!!! About the time calculated Pin
Yanbei at 20-Jan-12 8:01
memberYanbei20-Jan-12 8:01 
GeneralMy vote of 5 Pin
Big D at 4-Feb-11 9:20
memberBig D4-Feb-11 9:20 
GeneralMSDN remarks about using this High Performance Timer Pin
Member 3996853 at 31-Oct-10 0:51
memberMember 399685331-Oct-10 0:51 
GeneralRe: MSDN remarks about using this High Performance Timer Pin
Jay R. Wren at 17-May-11 6:45
memberJay R. Wren17-May-11 6:45 
GeneralMy vote of 5 Pin
Jibrohni at 12-Jul-10 2:35
memberJibrohni12-Jul-10 2:35 
Questiontimer code in c# to call in a method which id not static?? Pin
merryjoy000 at 12-Feb-09 1:38
membermerryjoy00012-Feb-09 1:38 
QuestionIs it possible to use this and trigger an Event? Pin
m.otte at 28-Jan-09 5:00
memberm.otte28-Jan-09 5:00 
Very nice. But I have a question.
I would like to create an Event that triggers every so many milliseconds. I only need 1ms accuracy at the most.
Now I’ve tried the easy way with the Clock method. But not matter what I try for the Interval prop, the results are not reliable (1ms Interval gets me 14,15,16ms between the printed time in my log file - 20ms gives me 30,31,32ms).
Your methods is more accurate but only used as a stopwatch. Is there a way to generate an Event using this method? So I can do something simple (write a line to a log file) every so many ms?


AnswerRe: Is it possible to use this and trigger an Event? Pin
NortuRE at 21-Aug-10 23:05
memberNortuRE21-Aug-10 23:05 
Generalnice class Pin
El Corazon at 7-Sep-08 9:40
memberEl Corazon7-Sep-08 9:40 
GeneralGarbage Colection in .NET Pin
Nguyen Thanh Luc at 22-May-08 18:22
memberNguyen Thanh Luc22-May-08 18:22 
GeneralSystem.Diagnostics.Stopwatch class Pin
Mach005 at 6-Apr-07 0:49
memberMach0056-Apr-07 0:49 
GeneralSome Corrections Pin
CobaltSoftware at 27-Mar-07 22:43
memberCobaltSoftware27-Mar-07 22:43 
GeneralGotcha's to watch out for Pin
Kodiak73 at 7-Feb-07 23:20
memberKodiak737-Feb-07 23:20 
GeneralMeasurement Pin
Gary Kirkham at 7-May-06 3:00
memberGary Kirkham7-May-06 3:00 
GeneralRe: Measurement Pin
SOUL_REAPER at 26-Dec-07 5:14
memberSOUL_REAPER26-Dec-07 5:14 
GeneralSeems pretty consistent to me! Pin
sklett at 11-Apr-06 14:49
membersklett11-Apr-06 14:49 
GeneralA clarification of the Sleep(0) call in Start() Pin
DrGary83 at 3-Jan-06 10:32
memberDrGary833-Jan-06 10:32 
GeneralStopwatch class from .net 2.0 framework ported .net 1.1 Pin
Paul Welter at 30-Jun-05 20:50
memberPaul Welter30-Jun-05 20:50 
GeneralErrors using code Pin
perkash at 7-Apr-05 1:14
memberperkash7-Apr-05 1:14 
GeneralRe: Errors using code Pin
Anonymous at 29-Sep-05 9:55
sussAnonymous29-Sep-05 9:55 
GeneralRe: Errors using code Pin
Ri Qen-Sin at 13-Sep-07 5:41
memberRi Qen-Sin13-Sep-07 5:41 
GeneralParameters should be ref long Pin
axelriet at 21-Feb-05 17:50
memberaxelriet21-Feb-05 17:50 
GeneralRe: Parameters should be ref long Pin
Anonymous at 18-Mar-05 4:39
sussAnonymous18-Mar-05 4:39 
GeneralRe: Parameters should be ref long Pin
axelriet at 18-Mar-05 8:13
memberaxelriet18-Mar-05 8:13 
QuestionWhat is this returning? Pin
jobobner at 6-Jan-05 5:52
memberjobobner6-Jan-05 5:52 
AnswerRe: What is this returning? Pin
Sander van Driel at 17-Jan-05 8:26
memberSander van Driel17-Jan-05 8:26 
GeneralRe: What is this returning? Pin
Big D at 7-Feb-11 5:15
memberBig D7-Feb-11 5:15 
GeneralInaccurate Timer duration Pin
Joseph McGowan at 3-Dec-04 5:10
memberJoseph McGowan3-Dec-04 5:10 
GeneralRe: Inaccurate Timer duration Pin
Anonymous at 12-Jan-05 9:28
sussAnonymous12-Jan-05 9:28 
GeneralRe: Inaccurate Timer duration Pin
Liu Junfeng at 5-Apr-05 4:04
memberLiu Junfeng5-Apr-05 4:04 
GeneralRe: Inaccurate Timer duration Pin
SuperMegaProg at 8-Mar-06 8:45
memberSuperMegaProg8-Mar-06 8:45 
GeneralRe: Inaccurate Timer duration Pin
Brian Clifton at 11-May-07 12:04
memberBrian Clifton11-May-07 12:04 
GeneralRe: Inaccurate Timer duration Pin
mbelshe at 13-Aug-07 12:05
membermbelshe13-Aug-07 12:05 
GeneralRe: Inaccurate Timer duration Pin
Brian Clifton at 26-Sep-07 11:36
memberBrian Clifton26-Sep-07 11:36 
GeneralOptimization Pin
Anonymous at 28-Sep-04 7:16
sussAnonymous28-Sep-04 7:16 
GeneralRe: Optimization Pin
Anonymous at 28-Sep-04 7:18
sussAnonymous28-Sep-04 7:18 
GeneralAdding a new propery for split timing Pin
jimboc42 at 6-Apr-04 7:01
memberjimboc426-Apr-04 7:01 
GeneralUsing this in a GPL application Pin
Bjornar Henden at 18-Sep-03 12:24
memberBjornar Henden18-Sep-03 12:24 
GeneralRe: Using this in a GPL application Pin
Daniel S. at 11-Oct-03 3:34
memberDaniel S.11-Oct-03 3:34 
GeneralRe: Using this in a GPL application Pin
Bjornar Henden at 11-Oct-03 3:52
memberBjornar Henden11-Oct-03 3:52 
eggie5 at 27-Jul-03 21:51
membereggie527-Jul-03 21:51 
GeneralRe: EXCELLENT Pin
Daniel S. at 16-Sep-03 22:52
memberDaniel S.16-Sep-03 22:52 
GeneralRe: EXCELLENT Pin
Jaime Olivares at 29-Oct-05 9:36
memberJaime Olivares29-Oct-05 9:36 
GeneralFor Windows CE.NET Pin
Frank Dzaebel at 25-Jul-03 5:23
memberFrank Dzaebel25-Jul-03 5:23 
GeneralRe: For Windows CE.NET Pin
Daniel S. at 25-Jul-03 5:54
memberDaniel S.25-Jul-03 5: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.150427.1 | Last Updated 30 Jul 2002
Article Copyright 2002 by Daniel Strigl
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid