C# Performance measurement helper classes

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    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()));
        }
    }