C# High Performance Counter

When accuracy is extremely important to you, you cannot rely on the standard DateTime or TimeSpan objects built into the .Net Framework. For real accuracy you need to go to the operating system itself. Here is a class which utilizes the operating system to count passing time.

using System.ComponentModel;

using System.Runtime.InteropServices;

using System.Threading;

 

namespace IPPoke.Library.Utilities

{

    public class HiPerformanceTimer

    {

        #region Private Fields

 

        [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 readonly long _freq;

 

        #endregion

 

        #region Initializers

 

        /// 

        /// Initializes a new instance of the  class.

        /// 

        public HiPerformanceTimer()

        {

            _startTime = 0;

            _stopTime  = 0;

 

            if (QueryPerformanceFrequency(out _freq) == false)

            {

                throw new Win32Exception();

            }

        }

 

        #endregion

 

        #region Public Methods

 

        /// 

        /// Starts this timer instance.

        /// 

        public void Start()

        {

            Thread.Sleep(0);

            QueryPerformanceCounter(out _startTime);

        }

 

        /// 

        /// Stops this timer instance.

        /// 

        public void Stop()

        {

            QueryPerformanceCounter(out _stopTime);

        }

 

        /// 

        /// Gets the duration of the timer in seconds.

        /// 

        /// The duration in seconds.

        public double Duration

        {

            get

            {

                return (_stopTime - _startTime) / (double) _freq;

            }

        }

 

        #endregion

    }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s