Last active
December 14, 2015 13:49
-
-
Save scvalex/5096359 to your computer and use it in GitHub Desktop.
A loop that executes an action a certain number of times per second.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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