]> git.lizzy.rs Git - shadowclad.git/blob - performance.c
Add frametime & fps metering
[shadowclad.git] / performance.c
1 #include <time.h>
2 #include <stdio.h> // TODO remove
3 #include <stdbool.h>
4
5 typedef struct timespec Timepoint;
6
7 static Timepoint lastDisplayTime;
8 static int frames = 0;
9 static bool meteringEnabled = false;
10
11 void initPerformanceMetering() {
12         if (clock_gettime(CLOCK_MONOTONIC, &lastDisplayTime) != 0) {
13                 fprintf(stderr, "Clock read failed, performance metering unavailable\n");
14         }
15         else {
16                 meteringEnabled = true;
17         }
18 }
19
20 void frameRendered() {
21         if (meteringEnabled) {
22                 ++frames;
23                 Timepoint now;
24                 
25                 if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) {
26                         fprintf(stderr, "Clock read failed, stopping performance metering\n");
27                         meteringEnabled = false;
28                         return;
29                 }
30                 
31                 time_t fullSeconds = now.tv_sec - lastDisplayTime.tv_sec;
32                 if (now.tv_nsec < lastDisplayTime.tv_nsec) --fullSeconds;
33                 
34                 if (fullSeconds > 0) {
35                         float seconds = (now.tv_nsec - lastDisplayTime.tv_nsec) / 1000000000.0f;
36                         seconds += (float) (now.tv_sec - lastDisplayTime.tv_sec);
37                         printf("frametime avg %.1f ms; fps avg %.f\n", (seconds / frames) * 1000.0f, (frames / seconds));
38                         lastDisplayTime = now;
39                         frames = 0;
40                 }
41         }
42 }