DeviceTimer.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6. namespace Aitex.Core.Util
  7. {
  8. public class DeviceTimer
  9. {
  10. [DllImport("Kernel32.dll")]
  11. private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
  12. [DllImport("Kernel32.dll")]
  13. private static extern bool QueryPerformanceFrequency(out long lpFrequency);
  14. private enum DeviceTimerState
  15. {
  16. TM_ST_IDLE = 0,
  17. TM_ST_BUSY = 1,
  18. TM_ST_TIMEOUT = 2,
  19. }
  20. DeviceTimerState _state;
  21. long _startTime;
  22. long _timeOut;
  23. double _freq;
  24. double _duration;
  25. public DeviceTimer()
  26. {
  27. long freq;
  28. if (QueryPerformanceFrequency(out freq) == false)
  29. throw new Exception("本计算机不支持高性能计数器");
  30. //得到每1ms的CPU计时TickCount数目
  31. _freq = (double)freq / 1000.0;
  32. SetState(DeviceTimerState.TM_ST_IDLE);
  33. QueryPerformanceCounter(out _startTime);
  34. _timeOut = _startTime;
  35. _duration = 0;
  36. }
  37. private void SetState(DeviceTimerState state)
  38. {
  39. _state = state;
  40. }
  41. private DeviceTimerState GetState()
  42. {
  43. return _state;
  44. }
  45. public double GetElapseTime()
  46. {
  47. long curCount;
  48. QueryPerformanceCounter(out curCount);
  49. return (double)(curCount - _startTime) / (double)_freq;
  50. }
  51. public double GetTotalTime()
  52. {
  53. return _duration;
  54. }
  55. public void Stop()
  56. {
  57. SetState(DeviceTimerState.TM_ST_IDLE);
  58. QueryPerformanceCounter(out _startTime);
  59. _timeOut = _startTime;
  60. _duration = 0;
  61. }
  62. public void Start(double delay_ms)
  63. {
  64. QueryPerformanceCounter(out _startTime);
  65. _timeOut = Convert.ToInt64(_startTime + delay_ms * _freq);
  66. SetState(DeviceTimerState.TM_ST_BUSY);
  67. _duration = delay_ms;
  68. }
  69. public void Restart(double delay_ms)
  70. {
  71. _timeOut = Convert.ToInt64(_startTime + delay_ms * _freq);
  72. SetState(DeviceTimerState.TM_ST_BUSY);
  73. _duration = delay_ms;
  74. }
  75. public bool IsTimeout()
  76. {
  77. if (_state == DeviceTimerState.TM_ST_IDLE)
  78. {
  79. }
  80. long curCount;
  81. QueryPerformanceCounter(out curCount);
  82. if (_state == DeviceTimerState.TM_ST_BUSY && (curCount >= _timeOut))
  83. {
  84. SetState(DeviceTimerState.TM_ST_TIMEOUT);
  85. return true;
  86. }
  87. else if (_state == DeviceTimerState.TM_ST_TIMEOUT)
  88. {
  89. return true;
  90. }
  91. return false;
  92. }
  93. public bool IsIdle()
  94. {
  95. return (_state == DeviceTimerState.TM_ST_IDLE);
  96. }
  97. }
  98. }