C++ Interval
Foreword
The following class will help us to measure time differences. We can (for example) use it very easily to find out how much time is left until the player can cast the next spell or find out how long a certain algorithm takes to execute:
Interval i;
myAlgorithm();
std::cout<<"it took: "<<i.value()<<"ms";
// => it took 10 ms (etc.)
About GetTickCount()
GetTickCount returns how long our system was running in milliseconds. Now if we do that once, wait a while, do it again and subtract both results, we can easily measure the time difference. Yet it's a bit more complicated (and unsafe) than the code sample above.
Example:
unsigned int start = GetTickCount();
myAlgorithm();
unsigned int elapsed = GetTickCount() - start;
std::cout<<"it took: "<<elapsed;
Why do we need a class for this?
The problem about GetTickCount() is that it starts at 0 again after a few days, because it's saved in a 4 byte value, which means it's just to small to save a lot of days in milliseconds. So our system will reach the point where the value is full, so what logically happens is that it starts at 0 again.
The result is that the difference between currentTime and lastTime will return something weird - which is bad, it would make our application be unstable or might even end in endless loops.
Let's wrap the GetTickCount() time measurement into a safe class that does all the hustle for us. If you want to learn more about where the problem exactly is, just read it up here.
Let's implement it in a safe way.
class Interval
{
private:
unsigned int initial_;
public:
// Ctor
inline Interval() : initial_(GetTickCount())
{
}
// Dtor
virtual ~Interval()
{
}
inline unsigned int value() const
{
return GetTickCount()-initial_;
}
};
Did you see how the current GetTickCount() is set in the constructor?
Here is how to use it:
## How to use it:
Interval i;
while (i.value() < 10) {
doStuff();
}
Summary
The implementation is simple as that, the reason why it works is much more complicated. For in-depth knowledge visit the link mentioned above, it contains an excellent explanation of the problem.