Click here to Skip to main content
11,409,138 members (47,667 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 ... PinmemberKris-I23-Apr-14 23:09 
GeneralMy vote of 5 PinmemberBesic Denis24-Apr-13 3:58 
SuggestionThis code is obsolete in .NET 2.0 and above [modified] PinmemberPavel Vladov17-Jul-12 23:18 
GeneralRe: This code is obsolete in .NET 2.0 and above - NOT WRT Silverlight Pinmemberdwrogers7-Feb-14 15:44 
GeneralMy vote of 1 Pinmemberhsnfrz25-May-12 1:51 
QuestionHelp ??????!!!!!!!! About the time calculated PinmemberYanbei20-Jan-12 8:01 
GeneralMy vote of 5 PinmemberBig D4-Feb-11 9:20 
GeneralMSDN remarks about using this High Performance Timer PinmemberMember 399685331-Oct-10 0:51 
GeneralRe: MSDN remarks about using this High Performance Timer PinmemberJay R. Wren17-May-11 6:45 
GeneralMy vote of 5 PinmemberJibrohni12-Jul-10 2:35 
Questiontimer code in c# to call in a method which id not static?? Pinmembermerryjoy00012-Feb-09 1:38 
QuestionIs it possible to use this and trigger an Event? Pinmemberm.otte28-Jan-09 5:00 
AnswerRe: Is it possible to use this and trigger an Event? PinmemberNortuRE21-Aug-10 23:05 
Generalnice class PinmemberEl Corazon7-Sep-08 9:40 
GeneralGarbage Colection in .NET PinmemberNguyen Thanh Luc22-May-08 18:22 
GeneralSystem.Diagnostics.Stopwatch class PinmemberMach0056-Apr-07 0:49 
GeneralSome Corrections PinmemberCobaltSoftware27-Mar-07 22:43 
GeneralGotcha's to watch out for PinmemberKodiak737-Feb-07 23:20 
GeneralMeasurement PinmemberGary Kirkham7-May-06 3:00 
GeneralRe: Measurement PinmemberSOUL_REAPER26-Dec-07 5:14 
GeneralSeems pretty consistent to me! Pinmembersklett11-Apr-06 14:49 
GeneralA clarification of the Sleep(0) call in Start() PinmemberDrGary833-Jan-06 10:32 
GeneralStopwatch class from .net 2.0 framework ported .net 1.1 PinmemberPaul Welter30-Jun-05 20:50 
GeneralErrors using code Pinmemberperkash7-Apr-05 1:14 
GeneralRe: Errors using code PinsussAnonymous29-Sep-05 9:55 
GeneralRe: Errors using code PinmemberRi Qen-Sin13-Sep-07 5:41 
GeneralParameters should be ref long Pinmemberaxelriet21-Feb-05 17:50 
GeneralRe: Parameters should be ref long PinsussAnonymous18-Mar-05 4:39 
GeneralRe: Parameters should be ref long Pinmemberaxelriet18-Mar-05 8:13 
QuestionWhat is this returning? Pinmemberjobobner6-Jan-05 5:52 
AnswerRe: What is this returning? PinmemberSander van Driel17-Jan-05 8:26 
GeneralRe: What is this returning? PinmemberBig D7-Feb-11 5:15 
GeneralInaccurate Timer duration PinmemberJoseph McGowan3-Dec-04 5:10 
GeneralRe: Inaccurate Timer duration PinsussAnonymous12-Jan-05 9:28 
GeneralRe: Inaccurate Timer duration PinmemberLiu Junfeng5-Apr-05 4:04 
GeneralRe: Inaccurate Timer duration PinmemberSuperMegaProg8-Mar-06 8:45 
GeneralRe: Inaccurate Timer duration PinmemberBrian Clifton11-May-07 12:04 
GeneralRe: Inaccurate Timer duration Pinmembermbelshe13-Aug-07 12:05 
GeneralRe: Inaccurate Timer duration PinmemberBrian Clifton26-Sep-07 11:36 
GeneralOptimization PinsussAnonymous28-Sep-04 7:16 
GeneralRe: Optimization PinsussAnonymous28-Sep-04 7:18 
GeneralAdding a new propery for split timing Pinmemberjimboc426-Apr-04 7:01 
GeneralUsing this in a GPL application PinmemberBjornar Henden18-Sep-03 12:24 
GeneralRe: Using this in a GPL application PinmemberDaniel S.11-Oct-03 3:34 
GeneralRe: Using this in a GPL application PinmemberBjornar Henden11-Oct-03 3:52 
GeneralEXCELLENT Pinmembereggie527-Jul-03 21:51 
GeneralRe: EXCELLENT PinmemberDaniel S.16-Sep-03 22:52 
GeneralRe: EXCELLENT PinmemberJaime Olivares29-Oct-05 9:36 
GeneralFor Windows CE.NET PinmemberFrank Dzaebel25-Jul-03 5:23 
GeneralRe: For Windows CE.NET PinmemberDaniel 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
Web01 | 2.8.150414.5 | Last Updated 30 Jul 2002
Article Copyright 2002 by Daniel Strigl
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid