方法效率测试工具

using System;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

namespace Common
{
    /// <summary>
    /// 方法效率测试工具类
    /// </summary>
    public static class CodeTimer
    {
        /// <summary>
        /// 在调用Time方法前先调用该方法预热
        /// </summary>
        public static void Initialize()
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Time("", 1, () => { });
        }

        /// <summary>
        /// 测试方法效率
        /// </summary>
        /// <param name="name">显示名称</param>
        /// <param name="iteration">循环次数</param>
        /// <param name="action">要测试的方法</param>
        public static void Time(string name, int iteration, Action action)
        {
            if (String.IsNullOrEmpty(name)) return;

            // 1.
            ConsoleColor currentForeColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(name);

            // 2.
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            int[] gcCounts = new int[GC.MaxGeneration + 1];
            for (int i = 0; i <= GC.MaxGeneration; i++)
            {
                gcCounts[i] = GC.CollectionCount(i);
            }

            // 3.
            Stopwatch watch = new Stopwatch();
            watch.Start();
            ulong cycleCount = GetCurrentThreadTimes();
            for (int i = 0; i < iteration; i++) action();
            ulong cpuCycles = GetCurrentThreadTimes() - cycleCount;
            watch.Stop();

            // 4.
            Console.ForegroundColor = currentForeColor;
            Console.WriteLine("\tTime Elapsed:\t" + watch.ElapsedMilliseconds.ToString("N0") + "ms");
            Console.WriteLine("\tCPU Cycles:\t" + cpuCycles.ToString("N0"));

            // 5.
            for (int i = 0; i <= GC.MaxGeneration; i++)
            {
                int count = GC.CollectionCount(i) - gcCounts[i];
                Console.WriteLine("\tGen " + i + ": \t\t" + count);
            }

            Console.WriteLine();
        }

        private static ulong GetCycleCount()
        {
            ulong cycleCount = 0;
            QueryThreadCycleTime(GetCurrentThread(), ref cycleCount);
            return cycleCount;
        }

        private static ulong GetCurrentThreadTimes()
        {
            ulong l;
            ulong kernelTime, userTimer;
            GetThreadTimes(GetCurrentThread(), out l, out l, out kernelTime,
               out userTimer);
            return kernelTime + userTimer;
        }

        //Vista和Server 2008中新的函数
        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool QueryThreadCycleTime(IntPtr threadHandle, ref ulong cycleTime);

        [DllImport("kernel32.dll")]
        static extern IntPtr GetCurrentThread();

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool GetThreadTimes(IntPtr hThread, out ulong lpCreationTime, out ulong lpExitTime, out ulong lpKernelTime, out ulong lpUserTime);
    }
}

 

调用:

    class Program
    {
        static void Main(string[] args)
        {
            //string aa = "";
            //Console.WriteLine(aa+"bb");
            //Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));


            int Count = 10000;
            CodeTimer.Initialize();

            CodeTimer.Time("测试名称", Count, () =>
            {
                Fun();
            });
        }

        static void Fun()
        {
            int Count = 1000;

            for (int i = 0; i < Count; i++)
            {
 
            }
        }

    }

结果:

posted @ 2014-04-17 14:43  zhushang  阅读(250)  评论(0)    收藏  举报