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

    }

}

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

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 )

Facebook photo

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

Connecting to %s