/* * fps-meter - Example program about how to measure frames per seconds * * Copyright (C) 2013 Antonio Ospite * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * 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 #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 tmp; unsigned int frames = 0; double nsecs = 0; float fps; while (1) { clock_gettime(CLOCK_MONOTONIC, &time_start); dbg("Start time: s: %ld, ns: %ld", time_start.tv_sec, time_start.tv_nsec); /* simulate some workload of about 60fps */ dbg("Doing some work, which takes about %d ns", NSEC_PER_SEC / 60); tmp.tv_sec = 0; tmp.tv_nsec = NSEC_PER_SEC / 60; clock_nanosleep(CLOCK_MONOTONIC, 0, &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); frames++; nsecs += (elapsed.tv_sec * NSEC_PER_SEC + elapsed.tv_nsec); if (nsecs >= NSEC_PER_SEC) { /* * if each frame takes less than a second, then just * printing 'frames' is enough, but if we want to * cover the case when a frame may take more than * a second, some calculations have to be done. */ fps = frames / (nsecs / NSEC_PER_SEC); printf("(frames: %d, nsecs: %f) FPS: %.2f\n", frames, nsecs, fps); nsecs = 0; frames = 0; } } return 0; }