C# Performance measurement helper classes

    public class PerformanceHelperClass
    {
        [DllImport("Kernel32.dll")]
        public static extern void QueryPerformanceCounter(ref long ticks);
        [DllImport("Kernel32.dll")]
        public static extern void QueryPerformanceFrequency(ref long freq);
        public static long GetCurrentTick()
        {
            long value = 0;
            QueryPerformanceCounter(ref value);
            return value;
        }

        public static long GetPerformanceFrequency()
        {
            long value = 0;
            QueryPerformanceFrequency(ref value);
            return value;
        }
    }

    public class PerformanceCouterable
    {
        protected long m_tickCreated;
        protected double m_frequency;

        public PerformanceCouterable()
        {
            ResetStartPerformanceTick();
        }

        protected void ResetStartPerformanceTick()
        {
            m_frequency = ((double)PerformanceHelperClass.GetPerformanceFrequency()) / 1000.0;
            m_tickCreated = PerformanceHelperClass.GetCurrentTick();
        }

        protected long GetPerformanceElapsedTick()
        {
            return PerformanceHelperClass.GetCurrentTick() - m_tickCreated;
        }

        protected double GetElapsedTime()
        {
            var elapsed = PerformanceHelperClass.GetCurrentTick() - m_tickCreated;
            return (double)elapsed / m_frequency;
        }
    }

    public class MesaureScope : PerformanceCouterable, IDisposable
    {
        private string m_scopeName = string.Empty;
        public MesaureScope(string name)
        {
            m_scopeName = name;
            Trace.WriteLine(string.Format("[MEASURE TIME - BEGIN] {0}", m_scopeName));
        }

        public void Dispose()
        {
            Trace.WriteLine(string.Format("[MEASURE TIME - END  ] {0} - {1}(ms)", m_scopeName, GetElapsedTime()));
        }
    }
Advertisements
This entry was posted in .NET, Performance, Programming. Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s