5,317,180 members and growing! (21,893 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

High-Performance Timer in C#

By Daniel Strigl

A C# class to provide exact time measurement in your applications.
C#Windows, .NET, .NET 1.0, Win2K, WinXPVS.NET2002, Visual Studio, Dev

Posted: 25 Jul 2002
Updated: 29 Jul 2002
Views: 210,788
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
38 votes for this Article.
Popularity: 6.84 Rating: 4.33 out of 5
0 votes, 0.0%
1
1 vote, 2.9%
2
3 votes, 8.8%
3
10 votes, 29.4%
4
20 votes, 58.8%
5

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


Daniel Strigl is living in Austria, where he is studying Computer Science at the University of Innsbruck and working as a Software Developer at a Semiconductor Equipment Company. In his spare time he is working as a Rafting-Guide at the Outdoor Company wasser-c-raft and as a Ski- and Snowboard-Instructor at some local skischools.

His programming experience includes C/C++, C#, Java, Matlab, Assembler, MFC, DirectDraw, DirectShow, OpenGL, STL, .NET, .NET Compact Framework and a little bit HTML, JavaScript and PHP. He has worked on Microcontrollers, Texas Instruments Calculators, Texas Instruments DSPs, Pocket PCs and on PCs. His favorite development tools are Eclipse, Microsoft eMbedded Visual C++, Microsoft Visual Studio 2005, Keil uVision and Texas Instruments Code Composer Studio.

Occupation: Software Developer
Location: Austria Austria

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 43 (Total in Forum: 43) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralGarbage Colection in .NETmemberNguyen Thanh Luc18:22 22 May '08  
GeneralSystem.Diagnostics.Stopwatch classmemberMach0050:49 6 Apr '07  
GeneralSome CorrectionsmemberCobaltSoftware22:43 27 Mar '07  
GeneralGotcha's to watch out formemberKodiak7323:20 7 Feb '07  
GeneralMeasurementmemberGary Kirkham3:00 7 May '06  
GeneralRe: MeasurementmemberSOUL_REAPER5:14 26 Dec '07  
GeneralSeems pretty consistent to me!membersklett14:49 11 Apr '06  
GeneralA clarification of the Sleep(0) call in Start()memberDrGary8310:32 3 Jan '06  
GeneralStopwatch class from .net 2.0 framework ported .net 1.1memberPaul Welter20:50 30 Jun '05  
GeneralErrors using codememberperkash1:14 7 Apr '05  
GeneralRe: Errors using codesussAnonymous9:55 29 Sep '05  
GeneralRe: Errors using codememberRi Qen-Sin5:41 13 Sep '07  
GeneralParameters should be ref longmemberaxelriet17:50 21 Feb '05  
GeneralRe: Parameters should be ref longsussAnonymous4:39 18 Mar '05  
GeneralRe: Parameters should be ref longmemberaxelriet8:13 18 Mar '05  
GeneralWhat is this returning?memberjobobner5:52 6 Jan '05  
GeneralRe: What is this returning?memberSander van Driel8:26 17 Jan '05  
GeneralInaccurate Timer durationmemberJoseph McGowan5:10 3 Dec '04  
GeneralRe: Inaccurate Timer durationsussAnonymous9:28 12 Jan '05  
GeneralRe: Inaccurate Timer durationmemberLiu Junfeng4:04 5 Apr '05  
GeneralRe: Inaccurate Timer durationmemberSuperMegaProg8:45 8 Mar '06  
GeneralRe: Inaccurate Timer durationmemberBrian Clifton12:04 11 May '07  
GeneralRe: Inaccurate Timer durationmembermbelshe12:05 13 Aug '07  
GeneralRe: Inaccurate Timer durationmemberBrian Clifton11:36 26 Sep '07  
GeneralOptimizationsussAnonymous7:16 28 Sep '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 29 Jul 2002
Editor: Nishant Sivakumar
Copyright 2002 by Daniel Strigl
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project