Ogre里面使用的时间系统, 可以供Windows程序复用, 源代码如下
Timer头文件:
class _OgreExport Timer : public TimerAlloc { private: clock_t mZeroClock; DWORD mStartTick; LONGLONG mLastTime; LARGE_INTEGER mStartTime; LARGE_INTEGER mFrequency; DWORD_PTR mTimerMask; public: /** Timer constructor. MUST be called on same thread that calls getMilliseconds() */ Timer(); ~Timer(); /** Method for setting a specific option of the Timer. These options are usually specific for a certain implementation of the Timer class, and may (and probably will) not exist across different implementations. reset() must be called after all setOption() calls. @par Current options supported are: <ul><li>"QueryAffinityMask" (DWORD): Set the thread affinity mask to be used to check the timer. If 'reset' has been called already this mask should overlap with the process mask that was in force at that point, and should be a power of two (a single core).</li></ul> @param strKey The name of the option to set @param pValue A pointer to the value - the size should be calculated by the timer based on the key @return On success, true is returned. @par On failure, false is returned. */ bool setOption( const String& strKey, const void* pValue ); /** Resets timer */ void reset(); /** Returns milliseconds since initialisation or last reset */ unsigned long getMilliseconds(); /** Returns microseconds since initialisation or last reset */ unsigned long getMicroseconds(); /** Returns milliseconds since initialisation or last reset, only CPU time measured */ unsigned long getMillisecondsCPU(); /** Returns microseconds since initialisation or last reset, only CPU time measured */ unsigned long getMicrosecondsCPU(); };
Timer实现文件:
//------------------------------------------------------------------------- Timer::Timer() : mTimerMask( 0 ) { reset(); } //------------------------------------------------------------------------- Timer::~Timer() { } //------------------------------------------------------------------------- bool Timer::setOption( const String & key, const void * val ) { if ( key == "QueryAffinityMask" ) { // Telling timer what core to use for a timer read DWORD newTimerMask = * static_cast < const DWORD * > ( val ); // Get the current process core mask DWORD_PTR procMask; DWORD_PTR sysMask; GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask); // If new mask is 0, then set to default behavior, otherwise check // to make sure new timer core mask overlaps with process core mask // and that new timer core mask is a power of 2 (i.e. a single core) if( ( newTimerMask == 0 ) || ( ( ( newTimerMask & procMask ) != 0 ) && Bitwise::isPO2( newTimerMask ) ) ) { mTimerMask = newTimerMask; return true; } } return false; } //------------------------------------------------------------------------- void Timer::reset() { // Get the current process core mask DWORD_PTR procMask; DWORD_PTR sysMask; GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask); // If procMask is 0, consider there is only one core available // (using 0 as procMask will cause an infinite loop below) if (procMask == 0) procMask = 1; // Find the lowest core that this process uses if( mTimerMask == 0 ) { mTimerMask = 1; while( ( mTimerMask & procMask ) == 0 ) { mTimerMask <<= 1; } } HANDLE thread = GetCurrentThread(); // Set affinity to the first core DWORD_PTR oldMask = SetThreadAffinityMask(thread, mTimerMask); // Get the constant frequency QueryPerformanceFrequency(&mFrequency); // Query the timer QueryPerformanceCounter(&mStartTime); mStartTick = GetTickCount(); // Reset affinity SetThreadAffinityMask(thread, oldMask); mLastTime = 0; mZeroClock = clock(); } //------------------------------------------------------------------------- unsigned long Timer::getMilliseconds() { LARGE_INTEGER curTime; HANDLE thread = GetCurrentThread(); // Set affinity to the first core DWORD_PTR oldMask = SetThreadAffinityMask(thread, mTimerMask); // Query the timer QueryPerformanceCounter(&curTime); // Reset affinity SetThreadAffinityMask(thread, oldMask); LONGLONG newTime = curTime.QuadPart - mStartTime.QuadPart; // scale by 1000 for milliseconds unsigned long newTicks = (unsigned long) (1000 * newTime / mFrequency.QuadPart); // detect and compensate for performance counter leaps // (surprisingly common, see Microsoft KB: Q274323) unsigned long check = GetTickCount() - mStartTick; signed long msecOff = (signed long)(newTicks - check); if (msecOff < -100 || msecOff > 100) { // We must keep the timer running forward :) LONGLONG adjust = (std::min)(msecOff * mFrequency.QuadPart / 1000, newTime - mLastTime); mStartTime.QuadPart += adjust; newTime -= adjust; // Re-calculate milliseconds newTicks = (unsigned long) (1000 * newTime / mFrequency.QuadPart); } // Record last time for adjust mLastTime = newTime; return newTicks; } //------------------------------------------------------------------------- unsigned long Timer::getMicroseconds() { LARGE_INTEGER curTime; HANDLE thread = GetCurrentThread(); // Set affinity to the first core DWORD_PTR oldMask = SetThreadAffinityMask(thread, mTimerMask); // Query the timer QueryPerformanceCounter(&curTime); // Reset affinity SetThreadAffinityMask(thread, oldMask); LONGLONG newTime = curTime.QuadPart - mStartTime.QuadPart; // get milliseconds to check against GetTickCount unsigned long newTicks = (unsigned long) (1000 * newTime / mFrequency.QuadPart); // detect and compensate for performance counter leaps // (surprisingly common, see Microsoft KB: Q274323) unsigned long check = GetTickCount() - mStartTick; signed long msecOff = (signed long)(newTicks - check); if (msecOff < -100 || msecOff > 100) { // We must keep the timer running forward :) LONGLONG adjust = (std::min)(msecOff * mFrequency.QuadPart / 1000, newTime - mLastTime); mStartTime.QuadPart += adjust; newTime -= adjust; } // Record last time for adjust mLastTime = newTime; // scale by 1000000 for microseconds unsigned long newMicro = (unsigned long) (1000000 * newTime / mFrequency.QuadPart); return newMicro; } //------------------------------------------------------------------------- unsigned long Timer::getMillisecondsCPU() { clock_t newClock = clock(); return (unsigned long)( (float)( newClock - mZeroClock ) / ( (float)CLOCKS_PER_SEC / 1000.0 ) ) ; } //------------------------------------------------------------------------- unsigned long Timer::getMicrosecondsCPU() { clock_t newClock = clock(); return (unsigned long)( (float)( newClock - mZeroClock ) / ( (float)CLOCKS_PER_SEC / 1000000.0 ) ) ; }
对于这个Timer类的分析, 在下面这个帖子中:
http://blog.csdn.net/hunter8777/archive/2011/02/24/6204719.aspx
使用:
void Root::populateFrameEvent(FrameEventTimeType type, FrameEvent& evtToUpdate) { unsigned long now = mTimer->getMilliseconds(); evtToUpdate.timeSinceLastEvent = calculateEventTime(now, FETT_ANY); evtToUpdate.timeSinceLastFrame = calculateEventTime(now, type); } //----------------------------------------------------------------------- Real Root::calculateEventTime(unsigned long now, FrameEventTimeType type) { // Calculate the average time passed between events of the given type // during the last mFrameSmoothingTime seconds. EventTimesQueue& times = mEventTimes[type]; times.push_back(now); if(times.size() == 1) return 0; // Times up to mFrameSmoothingTime seconds old should be kept unsigned long discardThreshold = static_cast<unsigned long>(mFrameSmoothingTime * 1000.0f); // Find the oldest time to keep EventTimesQueue::iterator it = times.begin(), end = times.end()-2; // We need at least two times while(it != end) { if (now - *it > discardThreshold) ++it; else break; } // Remove old times times.erase(times.begin(), it); return Real(times.back() - times.front()) / ((times.size()-1) * 1000); }