Advertisement
alaestor

[FGL Utility] windows only Stopwatch.h

Oct 11th, 2017 (edited)
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #ifndef STOPWATCH_H_INCLUDED
  2. #define STOPWATCH_H_INCLUDED
  3.  
  4. #define WINVER _WIN32_WINNT_WIN7
  5. #include <exception>
  6. #include <windows.h>
  7.  
  8. /*
  9.     Currently, only supporting windows platforms.
  10.  
  11.     This utility conforms to the Council of Ricks standard.
  12.     As well as the usual Future Gadget Laboratory standard.
  13.  
  14.     Writen in worldline Divergence 1.048596 by Alaestor.
  15.  
  16.     Time unit rounding accounts for negative values.
  17.     This utility is TARDIS and DeLorean safe.
  18.     Calling stop() before start() is acceptable behavior.
  19. */
  20.  
  21. class Stopwatch
  22. {
  23.     private:
  24.     const LARGE_INTEGER m_ticks_per_second;
  25.     LARGE_INTEGER m_start_tick;
  26.     LARGE_INTEGER m_end_tick;
  27.  
  28.     LARGE_INTEGER tps_init()
  29.     {
  30.         // TODO this value need only be acquired once.
  31.         // Unless ofcourse, a jump to lightspeed is made.
  32.         LARGE_INTEGER li;
  33.         if (!QueryPerformanceFrequency(&li)) throw std::runtime_error(
  34.                 "Stopwatch::QueryPerformanceFrequency() failed");
  35.         return li;
  36.     }
  37.  
  38.     long long tRound(const long double t) const
  39.     { return (t > 0 ? t + 500 : (t < 0 ? t - 500 : t)) / 1000; }
  40.  
  41.     public:
  42.  
  43.     void start()
  44.     { QueryPerformanceCounter(&m_start_tick); }
  45.  
  46.     void stop()
  47.     { QueryPerformanceCounter(&m_end_tick); }
  48.  
  49.     void reset()
  50.     { m_start_tick.QuadPart = m_end_tick.QuadPart = 0; }
  51.  
  52.     long long ticks() const
  53.     { return m_end_tick.QuadPart - m_start_tick.QuadPart; }
  54.  
  55.     long long nanoseconds() const
  56.     { return ticks() * 1000000000 / m_ticks_per_second.QuadPart; }
  57.  
  58.     long long microseconds() const
  59.     { return tRound(nanoseconds()); }
  60.  
  61.     long long milliseconds() const
  62.     { return tRound(nanoseconds() / 1000); }
  63.  
  64.     long long seconds() const
  65.     { return tRound(nanoseconds() / 1000000); }
  66.  
  67.     long long minutes() const
  68.     { return seconds() / 60; }
  69.  
  70.     long long hours() const
  71.     { return minutes() / 60; }
  72.  
  73.     long long days() const
  74.     { return hours() / 24; }
  75.  
  76.     explicit Stopwatch() :
  77.         m_ticks_per_second(tps_init())
  78.     {
  79.         m_start_tick.QuadPart = 0;
  80.         m_end_tick.QuadPart = 0;
  81.     }
  82.  
  83.     ~Stopwatch() = default;
  84. };
  85.  
  86. #endif // STOPWATCH_H_INCLUDED
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement