Click here to Skip to main content
Click here to Skip to main content

High-Performance Timer in C#

By , 29 Jul 2002
 

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Daniel Strigl
Austria Austria
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberBesic Denis24 Apr '13 - 2:58 
Simple and efficient.
SuggestionThis code is obsolete in .NET 2.0 and above [modified]memberPavel Vladov17 Jul '12 - 22:18 
Since .NET Framework 2.0 the Stopwatch class in the System.Diagnostics namespace can be used to measure elapsed time. Note that in order to get accurate times it is best to execute the tests and measure the times multiple times and then remove the lowest and the highest times. You can also use this approach to compare the performance of different code fragments/algorithms.
 
For more information take a look at the following article: Measure C# Code Performance

modified 5 Sep '12 - 4:09.

GeneralMy vote of 1memberhsnfrz25 May '12 - 0:51 
Bad
QuestionHelp ??????!!!!!!!! About the time calculatedmemberYanbei20 Jan '12 - 7:01 
I have a question on QueryPerformanceCounter.
 
If I called this both at the beginning and at the end of a code, I can get the elapsed time by:
 
elapsed time = (end counter - beginning counter) / frequency
 
This elapsed time is the processing time only for this period of the code spending on the CPU or the time elapsed when the code runs ?
 
Since there are many other applications running at the same time. Thanks for any comments.
GeneralMy vote of 5memberBig D4 Feb '11 - 8:20 
Thats what I was looking for. thank u very much.
GeneralMSDN remarks about using this High Performance TimermemberMember 399685330 Oct '10 - 23:51 
Please read the info on MSDN.
 
http://msdn.microsoft.com/en-us/library/ff650674.aspx[^]
 
Code example given in MSDN is nearly similar to the code Daniel supplied to us.
GeneralRe: MSDN remarks about using this High Performance TimermemberJay R. Wren17 May '11 - 5:45 
it appears to be obsolete in 2.0+ .net (so obsolete for 6yrs now)
 
The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.
 
from http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch%28VS.80%29.aspx
 
Big Grin | :-D
GeneralMy vote of 5memberJibrohni12 Jul '10 - 1:35 
really helped me out
Questiontimer code in c# to call in a method which id dynamic..ie not static??membermerryjoy00012 Feb '09 - 0:38 
i want a timer c# code in which i call a method which is dynamic..and which is to be exicuted every 30 mints
QuestionIs it possible to use this and trigger an Event?memberm.otte28 Jan '09 - 4: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?
 
Thanks!
 
Marco

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

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