BasicTimer.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. throw ref new Platform::FailureException();
  12. }
  13. Reset();
  14. }
  15. // Reset the timer to initial values.
  16. void Reset()
  17. {
  18. Update();
  19. m_startTime = m_currentTime;
  20. m_total = 0.0f;
  21. m_delta = 1.0f / 60.0f;
  22. }
  23. // Update the timer's internal values.
  24. void Update()
  25. {
  26. if (!QueryPerformanceCounter(&m_currentTime)) {
  27. throw ref new Platform::FailureException();
  28. }
  29. m_total = static_cast<float>(
  30. static_cast<double>(m_currentTime.QuadPart - m_startTime.QuadPart) /
  31. static_cast<double>(m_frequency.QuadPart));
  32. if (m_lastTime.QuadPart == m_startTime.QuadPart) {
  33. // If the timer was just reset, report a time delta equivalent to 60Hz
  34. // frame time.
  35. m_delta = 1.0f / 60.0f;
  36. } else {
  37. m_delta = static_cast<float>(
  38. static_cast<double>(m_currentTime.QuadPart - m_lastTime.QuadPart) /
  39. static_cast<double>(m_frequency.QuadPart));
  40. }
  41. m_lastTime = m_currentTime;
  42. }
  43. // Duration in seconds between the last call to Reset() and the last call to
  44. // Update().
  45. property float Total
  46. {
  47. float get() { return m_total; }
  48. }
  49. // Duration in seconds between the previous two calls to Update().
  50. property float Delta
  51. {
  52. float get() { return m_delta; }
  53. }
  54. private:
  55. LARGE_INTEGER m_frequency;
  56. LARGE_INTEGER m_currentTime;
  57. LARGE_INTEGER m_startTime;
  58. LARGE_INTEGER m_lastTime;
  59. float m_total;
  60. float m_delta;
  61. };