Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A loop that executes an action a certain number of times per second.
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
/* How many times per second do we want the code to run? */
const int frequency = 2;
/* Pretend to do something useful. */
void do_work() {
volatile int i;
for (i = 0; i < 10000000; ++i)
;
}
int main(int argc, char *argv[]) {
/* How long should each work unit take? */
long slice = (long)(1.0 / frequency * 1000000);
struct timeval beginning;
gettimeofday(&beginning, NULL);
struct timeval last_tick = beginning;
long total = 0;
int tick;
for (tick = 1; 1; ++tick) {
do_work();
struct timeval now;
gettimeofday(&now, NULL);
/* How much time has passed since the last tick? */
long usec_elapsed = (now.tv_sec - last_tick.tv_sec) * 1000000
+ (now.tv_usec - last_tick.tv_usec);
last_tick = now;
/* How time did we spend working this tick? */
long usec_work = (now.tv_sec - beginning.tv_sec) * 1000000
+ (now.tv_usec - beginning.tv_usec);
total += usec_elapsed;
printf("Worked for %ldus. Average time per tick: %ldus (%ldus since last).\n",
usec_work, total / tick, usec_elapsed);
/* Pause if appropriate. */
long usec_tosleep = slice - usec_work;
if (usec_tosleep > 0) {
printf("Sleeping for %ldus.\n", usec_tosleep);
usleep(usec_tosleep);
}
/* Prepare for the next tick. */
gettimeofday(&beginning, NULL);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.