HiPerfTimer.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.ComponentModel;
  3. using System.Runtime.InteropServices;
  4. using System.Threading;
  5. namespace Masuit.Tools.Systems
  6. {
  7. /// <summary>
  8. /// 纳秒级计时器
  9. /// </summary>
  10. public class HiPerfTimer
  11. {
  12. [DllImport("Kernel32.dll")]
  13. private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
  14. [DllImport("Kernel32.dll")]
  15. private static extern bool QueryPerformanceFrequency(out long lpFrequency);
  16. private long _startTime;
  17. private long _stopTime;
  18. private readonly long _freq;
  19. /// <summary>
  20. /// 纳秒计数器
  21. /// </summary>
  22. public HiPerfTimer()
  23. {
  24. _startTime = 0;
  25. _stopTime = 0;
  26. if (QueryPerformanceFrequency(out _freq) == false)
  27. {
  28. // 不支持高性能计数器
  29. throw new Win32Exception();
  30. }
  31. }
  32. /// <summary>
  33. /// 开始计时器
  34. /// </summary>
  35. public void Start()
  36. {
  37. // 来让等待线程工作
  38. Thread.Sleep(0);
  39. QueryPerformanceCounter(out _startTime);
  40. }
  41. /// <summary>
  42. /// 启动一个新的计时器
  43. /// </summary>
  44. /// <returns></returns>
  45. public static HiPerfTimer StartNew()
  46. {
  47. HiPerfTimer timer = new HiPerfTimer();
  48. timer.Start();
  49. return timer;
  50. }
  51. /// <summary>
  52. /// 停止计时器
  53. /// </summary>
  54. public void Stop()
  55. {
  56. QueryPerformanceCounter(out _stopTime);
  57. }
  58. /// <summary>
  59. /// 时器经过时间(单位:秒)
  60. /// </summary>
  61. public double Duration => (_stopTime - _startTime) / (double)_freq;
  62. /// <summary>
  63. /// 执行一个方法并测试执行时间
  64. /// </summary>
  65. /// <param name="action"></param>
  66. /// <returns></returns>
  67. public static double Execute(Action action)
  68. {
  69. var timer = new HiPerfTimer();
  70. timer.Start();
  71. action();
  72. timer.Stop();
  73. return timer.Duration;
  74. }
  75. }
  76. }