1 /* 2 * Copyright (c) 2006 3 * Francois Dumont 4 * 5 * This material is provided "as is", with absolutely no warranty expressed 6 * or implied. Any use is at your own risk. 7 * 8 * Permission to use or copy this software for any purpose is hereby granted 9 * without fee, provided the above notices are retained on all copies. 10 * Permission to modify the code and to distribute modified code is granted, 11 * provided the above notices are retained, and a notice that the code was 12 * modified is included with the above copyright notice. 13 * 14 */ 15 16 #ifndef CPPUNIT_TIMER_H 17 #define CPPUNIT_TIMER_H 18 19 #if defined (_WIN32) 20 # define CPPUNIT_WIN32_TIMER 21 # include <windows.h> 22 #endif 23 24 class Timer { 25 public: Timer()26 Timer() { 27 #if defined (CPPUNIT_WIN32_TIMER) 28 m_start.LowPart = m_restart.LowPart = m_stop.LowPart = 0; 29 m_start.HighPart = m_restart.HighPart = m_stop.HighPart = 0; 30 QueryPerformanceFrequency(&m_frequency); 31 #endif 32 } 33 start()34 void start() { 35 #if defined (CPPUNIT_WIN32_TIMER) 36 QueryPerformanceCounter(&m_start); 37 #endif 38 } 39 restart()40 void restart() { 41 #if defined (CPPUNIT_WIN32_TIMER) 42 QueryPerformanceCounter(&m_restart); 43 if (m_start.HighPart == 0 && m_start.LowPart == 0) { 44 m_start = m_restart; 45 } 46 #endif 47 } 48 stop()49 void stop() { 50 #if defined (CPPUNIT_WIN32_TIMER) 51 LARGE_INTEGER stop; 52 QueryPerformanceCounter(&stop); 53 if ((m_stop.HighPart != 0 || m_stop.LowPart != 0) && 54 m_restart.HighPart != 0 && m_restart.LowPart != 0) { 55 m_stop.HighPart += (stop.HighPart - m_restart.HighPart); 56 if (stop.LowPart < m_restart.LowPart) { 57 if (m_restart.LowPart - stop.LowPart > m_stop.LowPart) { 58 m_stop.HighPart -= 1; 59 } 60 m_stop.LowPart -= m_restart.LowPart - stop.LowPart; 61 } 62 else { 63 if (stop.LowPart - m_restart.LowPart > 0xFFFFFFFF - m_stop.LowPart) { 64 m_stop.HighPart += 1; 65 } 66 m_stop.LowPart += stop.LowPart - m_restart.LowPart; 67 } 68 } 69 else { 70 m_stop = stop; 71 } 72 #endif 73 } 74 elapsedMilliseconds()75 double elapsedMilliseconds() const { 76 #if defined (CPPUNIT_WIN32_TIMER) 77 LARGE_INTEGER elapsed; 78 elapsed.HighPart = m_stop.HighPart - m_start.HighPart; 79 elapsed.LowPart = m_stop.LowPart - m_start.LowPart; 80 return (double)elapsed.QuadPart / (double)m_frequency.QuadPart * 1000; 81 #else 82 return 0; 83 #endif 84 } 85 supported()86 static bool supported() { 87 #if defined (CPPUNIT_WIN32_TIMER) 88 return true; 89 #else 90 return false; 91 #endif 92 } 93 94 private: 95 #if defined (CPPUNIT_WIN32_TIMER) 96 LARGE_INTEGER m_frequency; 97 LARGE_INTEGER m_start, m_stop, m_restart; 98 #endif 99 }; 100 101 #endif 102