我整理了老赵的一个测试的工具类,别的没做改变,只是把类名和方法名改成了我自己比较习惯的名称而已。

     不多说了,代码如下:
    

     /// <summary>
    /// 代码性能测试器
    /// </summary>
    public static class CodePerformanceTester
    {
        /// <summary>
        /// 初始化器,首先它会把当前进程及当前线程的优先级设为最高,这样便可以相对减少操作系统在调度上造成的干扰。
        /// 然后调用一次Time方法进行“预热”,让JIT将IL编译成本地代码,让Time方法尽快“进入状态”。
        /// 该方法要在测试之前执行。
        /// </summary>
        public static void Initialize()
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Test("", 1, () => { });
        }

        /// <summary>
        /// 性能测试的核心方法,打印出花费时间,消耗的CPU时钟周期,以及各代垃圾收集的回收次数
        /// </summary>
        /// <param name="name">测试实例的名称,便于记忆</param>
        /// <param name="iteration">迭代次数</param>
        /// <param name="action">所要执行测试的方法</param>
        public static void Test(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进行收集,并记录目前各代已经收集的次数。
            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.执行代码,记录下消耗的时间及CPU时钟周期。
            Stopwatch watch = new Stopwatch();
            watch.Start();
            ulong cycleCount = GetCycleCount();
            for (int i = 0; i < iteration; i++) action();
            ulong cpuCycles = GetCycleCount() - cycleCount;
            watch.Stop();

            // 4.恢复控制台默认前景色,并打印出消耗时间及CPU时钟周期。
            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();
        }

        /// <summary>
        /// 获取周期次数
        /// </summary>
        /// <returns>返回线程的周期次数</returns>
        private static ulong GetCycleCount()
        {
            ulong cycleCount = 0;
            QueryThreadCycleTime(GetCurrentThread(), ref cycleCount);
            return cycleCount;
        }

        /// <summary>
        /// 获取线程周期时间
        /// </summary>
        /// <param name="threadHandle">线程句柄</param>
        /// <param name="cycleTime">返回周期时间</param>
        /// <returns>返回布尔值,true表示获取线程周期实现成功,false表示获取线程周期时间失败</returns>
        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool QueryThreadCycleTime(IntPtr threadHandle, ref ulong cycleTime);

        /// <summary>
        /// 获取当前线程引用句柄
        /// </summary>
        /// <returns>返回当前线程的引用句柄</returns>
        [DllImport("kernel32.dll")]
        static extern IntPtr GetCurrentThread();
    }

   以上就是完整代码,拷贝就可以使用,记录下来,以防忘记。

posted on 2016-11-15 15:05  可均可可  阅读(1177)  评论(2编辑  收藏  举报