CpuClock.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System.Diagnostics;
  2. namespace AIDiagnosisDemo.GC
  3. {
  4. internal class CpuClock
  5. {
  6. #region Fields and Events 
  7. // Fields 
  8. private static double _cpuFrequency;
  9. private double _startTime;
  10. #endregion Fields and Events 
  11. #region Methods 
  12. // Constructors 
  13. public CpuClock()
  14. {
  15. _startTime = GetCurrentTimestamp();
  16. }
  17. static CpuClock()
  18. {
  19. long counter;
  20. counter = Stopwatch.Frequency;
  21. _cpuFrequency = counter;
  22. }
  23. // Methods 
  24. private static long QueryPerformanceCounter()
  25. {
  26. long counter;
  27. counter = Stopwatch.GetTimestamp();
  28. return counter;
  29. }
  30. private static long QueryPerformanceFrequency()
  31. {
  32. long cpuFrequency;
  33. cpuFrequency = Stopwatch.Frequency;
  34. return cpuFrequency;
  35. }
  36. private static double GetCurrentTimestamp()
  37. {
  38. long newCounter = QueryPerformanceCounter();
  39. return newCounter / (double)_cpuFrequency;
  40. }
  41. /// <summary>
  42. /// Returns the spent time(as second) after the <c>CpuClock</c> is created
  43. /// </summary>
  44. /// <returns></returns>
  45. public double GetTime()
  46. {
  47. return TotalSeconds;
  48. }
  49. /// <summary>
  50. /// Returns the spent time(as second) after system start
  51. /// </summary>
  52. /// <returns></returns>
  53. public static double Current
  54. {
  55. get { return GetCurrentTimestamp(); }
  56. }
  57. public double StartTime
  58. {
  59. get { return _startTime; }
  60. }
  61. public double TotalSeconds
  62. {
  63. get { return (Current - _startTime); }
  64. }
  65. public double TotalMilliSeconds
  66. {
  67. get { return (Current - _startTime) * 1000; }
  68. }
  69. public static CpuClock Now
  70. {
  71. get
  72. {
  73. return new CpuClock();
  74. }
  75. }
  76. #endregion Methods 
  77. }
  78. }