Rate counter: Difference between revisions
Content added Content deleted
(Create task, C example) |
(Add a simple C++ translation.) |
||
Line 80: | Line 80: | ||
// Note that we did something. |
// Note that we did something. |
||
tic_rate(&rateWatch); |
tic_rate(&rateWatch); |
||
} |
|||
return 0; |
|||
} |
|||
</lang> |
|||
=={{header|C++}}== |
|||
This code defines the counter as a class, '''CRateState'''. The counter's period is configured as an argument to its constructor, and the rest of the counter state is kept as class members. A member function '''Tick()''' manages updating the counter state, and reports the tic rate if the configured period has elapsed. |
|||
<lang cpp>#include <iostream> |
|||
#include <time.h> |
|||
// We only get one-second precision on most systems, as |
|||
// time_t only holds seconds. |
|||
class CRateState |
|||
{ |
|||
protected: |
|||
time_t m_lastFlush; |
|||
time_t m_period; |
|||
size_t m_tickCount; |
|||
public: |
|||
CRateState(time_t period); |
|||
void Tick(); |
|||
}; |
|||
CRateState::CRateState(time_t period) |
|||
{ |
|||
m_lastFlush = time(NULL); |
|||
m_period = period; |
|||
m_tickCount = 0; |
|||
} |
|||
void CRateState::Tick() |
|||
{ |
|||
m_tickCount += 1; |
|||
time_t now = time(NULL); |
|||
if((now - m_lastFlush) >= m_period) |
|||
{ |
|||
//TPS Report |
|||
size_t tps = 0.0; |
|||
if(m_tickCount > 0) |
|||
tps = m_tickCount / (now - m_lastFlush); |
|||
std::cout << tps << " tics per second" << std::endl; |
|||
//Reset |
|||
m_tickCount = 0; |
|||
m_lastFlush = now; |
|||
} |
|||
} |
|||
// A stub function that simply represents whatever it is |
|||
// that we want to multiple times. |
|||
void something_we_do() |
|||
{ |
|||
// We use volatile here, as many compilers will optimize away |
|||
// the for() loop otherwise, even without optimizations |
|||
// explicitly enabled. |
|||
// |
|||
// volatile tells the compiler not to make any assumptions |
|||
// about the variable, implying that the programmer knows more |
|||
// about that variable than the compiler, in this case. |
|||
volatile size_t anchor = 0; |
|||
for(size_t x = 0; x < 0xffff; ++x) |
|||
{ |
|||
anchor = x; |
|||
} |
|||
} |
|||
int main() |
|||
{ |
|||
time_t start = time(NULL); |
|||
CRateState rateWatch(5); |
|||
time_t latest = start; |
|||
// Loop for twenty seconds |
|||
for(latest = start; (latest - start) < 20; latest = time(NULL)) |
|||
{ |
|||
// Do something. |
|||
something_we_do(); |
|||
// Note that we did something. |
|||
rateWatch.Tick(); |
|||
} |
} |
||