1
我正在讀一些書,我給了一些計時器的實現。然而,這本書中沒有關於計時器的真實解釋,我想知道他爲什麼要做某些事情。爲什麼更新基於隨機值的計時器?
代碼:
// Desc: Use this class to regulate code flow (for an update function say)
// Instantiate the class with the frequency you would like your code
// section to flow (like 10 times per second) and then only allow
// the program flow to continue if Ready() returns true
class Regulator
{
private:
//the time period between updates
double m_dUpdatePeriod;
//the next time the regulator allows code flow
DWORD m_dwNextUpdateTime;
public:
Regulator(double NumUpdatesPerSecondRqd)
{
m_dwNextUpdateTime = (DWORD)(timeGetTime()+RandFloat()*1000);
if (NumUpdatesPerSecondRqd > 0)
{
m_dUpdatePeriod = 1000.0/NumUpdatesPerSecondRqd;
}
else if (isEqual(0.0, NumUpdatesPerSecondRqd))
{
m_dUpdatePeriod = 0.0;
}
else if (NumUpdatesPerSecondRqd < 0)
{
m_dUpdatePeriod = -1;
}
}
//returns true if the current time exceeds m_dwNextUpdateTime
bool isReady()
{
//if a regulator is instantiated with a zero freq then it goes into
//stealth mode (doesn't regulate)
if (isEqual(0.0, m_dUpdatePeriod)) return true;
//if the regulator is instantiated with a negative freq then it will
//never allow the code to flow
if (m_dUpdatePeriod < 0) return false;
DWORD CurrentTime = timeGetTime();
//the number of milliseconds the update period can vary per required
//update-step. This is here to make sure any multiple clients of this class
//have their updates spread evenly
static const double UpdatePeriodVariator = 10.0;
if (CurrentTime >= m_dwNextUpdateTime)
{
m_dwNextUpdateTime = (DWORD)(CurrentTime + m_dUpdatePeriod + RandInRange(-UpdatePeriodVariator, UpdatePeriodVariator));
return true;
}
return false;
}
};
isEqual()
檢查給定的兩個雙打之間的差異是否比0.00更小...... 1
RandInRange()
返回給定範圍內的隨機數
我不我真的不明白爲什麼他要給m_dwNextUpdateTime
添加一個給定範圍的隨機數。儘管他「解釋」,但對我來說似乎沒有任何意義。
任何人都可以幫忙嗎?
不知道C++,我想這可能是因爲它只是宣佈一些隨機值作爲某種類型的樣品,就可以讓你瞭解,你可以跟他們做什麼呢? – 2011-12-14 02:26:02
@JerryDodge懷疑,因爲這個類實際上有一個明確的用途。另外,本書並不打算教導如何使用隨機值。 – xcrypt 2011-12-14 02:28:04