]> git.lizzy.rs Git - shadowclad.git/blob - src/engine/performance.c
Add copyright and license notices in source code
[shadowclad.git] / src / engine / performance.c
1 /**
2  * Copyright 2019-2020 Iwo 'Outfrost' Bujkiewicz
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8
9 #ifndef _POSIX_C_SOURCE
10 #define _POSIX_C_SOURCE 199309L
11 #endif
12
13 #include "performance.h"
14
15 #include <stdbool.h>
16 #include <stdio.h> // TODO remove
17 #include <time.h>
18
19 #include "logger.h"
20
21 typedef struct timespec Timepoint;
22
23 static Timepoint lastDisplayTime;
24 static int frames = 0;
25 static bool meteringEnabled = false;
26
27
28
29 void initPerformanceMetering() {
30         if (clock_gettime(CLOCK_MONOTONIC, &lastDisplayTime) != 0) {
31                 logWarning("Clock read failed, performance metering unavailable");
32         }
33         else {
34                 meteringEnabled = true;
35         }
36 }
37
38 void frameRendered() {
39         if (meteringEnabled) {
40                 ++frames;
41                 Timepoint now;
42
43                 if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) {
44                         logWarning("Clock read failed, stopping performance metering");
45                         meteringEnabled = false;
46                         return;
47                 }
48
49                 time_t fullSeconds = now.tv_sec - lastDisplayTime.tv_sec;
50                 if (now.tv_nsec < lastDisplayTime.tv_nsec) --fullSeconds;
51
52                 if (fullSeconds > 0) {
53                         float seconds = (now.tv_nsec - lastDisplayTime.tv_nsec) / 1000000000.0f;
54                         seconds += (float) (now.tv_sec - lastDisplayTime.tv_sec);
55                         // This goes to STDOUT because it's, uh, temporary
56                         printf("frametime avg %.1f ms; fps avg %.f\n", (seconds / frames) * 1000.0f, (frames / seconds));
57                         lastDisplayTime = now;
58                         frames = 0;
59                 }
60         }
61 }