CodeTimer.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading;
  8. namespace Ant.Common
  9. {
  10. public static class CodeTimer
  11. {
  12. public static void Initialize()
  13. {
  14. Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
  15. Thread.CurrentThread.Priority = ThreadPriority.Highest;
  16. Time("", 1, () => { });
  17. }
  18. public static void Time(string name, int iteration, Action action)
  19. {
  20. if (String.IsNullOrEmpty(name)) return;
  21. // 1.
  22. ConsoleColor currentForeColor = Console.ForegroundColor;
  23. Console.ForegroundColor = ConsoleColor.Yellow;
  24. Console.WriteLine(name);
  25. // 2.
  26. GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
  27. int[] gcCounts = new int[GC.MaxGeneration + 1];
  28. for (int i = 0; i <= GC.MaxGeneration; i++)
  29. {
  30. gcCounts[i] = GC.CollectionCount(i);
  31. }
  32. // 3.
  33. Stopwatch watch = new Stopwatch();
  34. watch.Start();
  35. ulong cycleCount = GetCycleCount();
  36. for (int i = 0; i < iteration; i++) action();
  37. ulong cpuCycles = GetCycleCount() - cycleCount;
  38. watch.Stop();
  39. // 4.
  40. Console.ForegroundColor = currentForeColor;
  41. Console.WriteLine("\t花费时间:\t" + watch.ElapsedMilliseconds.ToString("N0") + "ms");
  42. Console.WriteLine("\tCPU时钟周期:\t" + cpuCycles.ToString("N0"));
  43. // 5.
  44. for (int i = 0; i <= GC.MaxGeneration; i++)
  45. {
  46. int count = GC.CollectionCount(i) - gcCounts[i];
  47. Console.WriteLine("\t垃圾收集的回收次数 " + i + ": \t\t" + count);
  48. }
  49. Console.WriteLine();
  50. }
  51. private static ulong GetCycleCount()
  52. {
  53. ulong cycleCount = 0;
  54. QueryThreadCycleTime(GetCurrentThread(), ref cycleCount);
  55. return cycleCount;
  56. }
  57. [DllImport("kernel32.dll")]
  58. [return: MarshalAs(UnmanagedType.Bool)]
  59. static extern bool QueryThreadCycleTime(IntPtr threadHandle, ref ulong cycleTime);
  60. [DllImport("kernel32.dll")]
  61. static extern IntPtr GetCurrentThread();
  62. }
  63. }