Rate counter

From Rosetta Code
Revision as of 22:25, 5 December 2009 by MikeMol (talk | contribs) (Create task, C example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Rate counter
You are encouraged to solve this task according to the task description, using any language you may know.

Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.

Multiple approaches are allowed (even preferable), so long as they accomplish these goals:

  • Run twenty seconds worth of jobs and/or two hundred jobs.
  • Report at least three distinct times.

C

This code stores all of the data of the rate counter and its configuration in an instance of a struct named rate_state_s, and a function named tic_rate is called on that struct instance every time we complete a job. If a configured time has elapsed, tic_rate calculates and reports the tic rate, and resets the counter.

<lang c>#include <stdio.h>

  1. include <time.h>

// We only get one-second precision on most systems, as // time_t only holds seconds. struct rate_state_s {

   time_t lastFlush;
   time_t period;
   size_t tickCount;

};

void tic_rate(struct rate_state_s* pRate) {

   pRate->tickCount += 1;
   time_t now = time(NULL);
   if((now - pRate->lastFlush) >= pRate->period)
   {
       //TPS Report
       size_t tps = 0.0;
       if(pRate->tickCount > 0)
           tps = pRate->tickCount / (now - pRate->lastFlush);
       printf("%u tics per second.\n", tps);
       //Reset
       pRate->tickCount = 0;
       pRate->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;
   size_t x = 0;
   for(x = 0; x < 0xffff; ++x)
   {
       anchor = x;
   }

}

int main() {

   time_t start = time(NULL);
   struct rate_state_s rateWatch;
   rateWatch.lastFlush = start;
   rateWatch.tickCount = 0;
   rateWatch.period = 5; // Report every five seconds.
   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.
       tic_rate(&rateWatch);
   }
   return 0;

} </lang>