我正在读一本书,我给了一些计时器实现。然而,书中的计时器没有真正的解释,我想知道他为什么做某些事情。
代码:
// 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
添加给定范围的随机数。即使他“解释”,但对我来说似乎没有任何意义。
有人可以帮忙吗?
答案 0 :(得分:3)
// This is here to make sure any multiple clients of this class
//have their updates spread evenly
当您同时多次运行相同的代码时,会引入随机性以降低争用。如果所有客户使用完全相同的间隔,他们可能会全部醒来&#34;在同一时间,这可能是不幸的负载。引入一些随机变化使他们更多地展开他们的活动。