BasicTimer.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #pragma once
  2. #include <wrl.h>
  3. // Helper class for basic timing.
  4. ref class BasicTimer sealed
  5. {
  6. public:
  7. // Initializes internal timer values.
  8. BasicTimer()
  9. {
  10. if (!QueryPerformanceFrequency(&m_frequency))
  11. {
  12. throw ref new Platform::FailureException();
  13. }
  14. Reset();
  15. }
  16. // Reset the timer to initial values.
  17. void Reset()
  18. {
  19. Update();
  20. m_startTime = m_currentTime;
  21. m_total = 0.0f;
  22. m_delta = 1.0f / 60.0f;
  23. }
  24. // Update the timer's internal values.
  25. void Update()
  26. {
  27. if (!QueryPerformanceCounter(&m_currentTime))
  28. {
  29. throw ref new Platform::FailureException();
  30. }
  31. m_total = static_cast<float>(
  32. static_cast<double>(m_currentTime.QuadPart - m_startTime.QuadPart) /
  33. static_cast<double>(m_frequency.QuadPart)
  34. );
  35. if (m_lastTime.QuadPart == m_startTime.QuadPart)
  36. {
  37. // If the timer was just reset, report a time delta equivalent to 60Hz frame time.
  38. m_delta = 1.0f / 60.0f;
  39. }
  40. else
  41. {
  42. m_delta = static_cast<float>(
  43. static_cast<double>(m_currentTime.QuadPart - m_lastTime.QuadPart) /
  44. static_cast<double>(m_frequency.QuadPart)
  45. );
  46. }
  47. m_lastTime = m_currentTime;
  48. }
  49. // Duration in seconds between the last call to Reset() and the last call to Update().
  50. property float Total
  51. {
  52. float get() { return m_total; }
  53. }
  54. // Duration in seconds between the previous two calls to Update().
  55. property float Delta
  56. {
  57. float get() { return m_delta; }
  58. }
  59. private:
  60. LARGE_INTEGER m_frequency;
  61. LARGE_INTEGER m_currentTime;
  62. LARGE_INTEGER m_startTime;
  63. LARGE_INTEGER m_lastTime;
  64. float m_total;
  65. float m_delta;
  66. };