Click here to Skip to main content
13,445,901 members (37,068 online)
Click here to Skip to main content
Add your own
alternative version


131 bookmarked
Posted 25 Jul 2002

High-Performance Timer in C#

, 29 Jul 2002
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

You may also be interested in...

Comments and Discussions

QuestionHelp ??????!!!!!!!! About the time calculated Pin
Yanbei20-Jan-12 7:01
memberYanbei20-Jan-12 7:01 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01-2016 | 2.8.180314.2 | Last Updated 30 Jul 2002
Article Copyright 2002 by Daniel Strigl
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid