X-Git-Url: https://git.ao2.it/experiments/fps-limit.git/blobdiff_plain/ce00a8af50035f3db13f1795061d55e943f2e969..5b5e421a8ef9318f08455f0aa30d1278e1e8ca9f:/fps-limit.c diff --git a/fps-limit.c b/fps-limit.c index 7759349..2c24807 100644 --- a/fps-limit.c +++ b/fps-limit.c @@ -17,62 +17,26 @@ * along with this program. If not, see . */ -#include -#include - -#ifdef DEBUG -#define dbg(...) \ - do { \ - printf(__VA_ARGS__); \ - printf("\n"); \ - fflush(stdout); \ - } while(0) -#else -#define dbg(...) do {} while(0) -#endif +#include "fps-limit.h" #define FPS 60 -#define NSEC_PER_SEC 1000000000 - -#define timespecsub(a, b, result) \ - do { \ - (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ - (result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \ - if ((result)->tv_nsec < 0) { \ - --(result)->tv_sec; \ - (result)->tv_nsec += 1000000000; \ - } \ - } while(0) - int main(void) { - struct timespec time_start; - struct timespec time_end; - struct timespec elapsed; - struct timespec remaining = {0, 0}; - + struct fps_limit_stats stats; struct timespec tmp; + fps_limit_init(&stats, FPS); while (1) { - clock_gettime(CLOCK_MONOTONIC, &time_start); - dbg("Start time: s: %ld, ns: %ld", time_start.tv_sec, time_start.tv_nsec); + fps_limit_dbg("Doing some work, minimum: %dns", NSEC_PER_SEC / FPS); - dbg("Doing some work, max: %d", NSEC_PER_SEC / FPS); + /* simulate a shorter workload */ tmp.tv_sec = 0; tmp.tv_nsec = (NSEC_PER_SEC / FPS) * 2 / 3; nanosleep(&tmp, NULL); - clock_gettime(CLOCK_MONOTONIC, &time_end); - dbg("End time: s: %ld, ns: %ld", time_end.tv_sec, time_end.tv_nsec); - timespecsub(&time_end, &time_start, &elapsed); - dbg("Elapsed s: %ld ns: %ld", elapsed.tv_sec, elapsed.tv_nsec); - if (elapsed.tv_sec == 0 && elapsed.tv_nsec < NSEC_PER_SEC / FPS) { - /* remaining delay, _relative_ to time_end */ - remaining.tv_nsec = (NSEC_PER_SEC / FPS) - elapsed.tv_nsec; - dbg("Sleeping for: ns: %ld", remaining.tv_nsec); - clock_nanosleep(CLOCK_MONOTONIC, 0, &remaining, NULL); - } + /* and wait for the delay imposed by the limit */ + fps_limit_sleep(&stats); } return 0;