Banjo API 1.0.0-rc.2
Low-level C99 game development API
Loading...
Searching...
No Matches
stopwatch.c

Using stopwatch for precise timing and delta time measurements.

Using stopwatch for precise timing and delta time measurements.A stopwatch tracks both total elapsed time and delta time (time since last measurement). This is essential for frame-independent game logic, animation, and performance profiling.

It is a plain console program with its own loop rather than an App (bj_run_app) program: there is no window or event handling to drive, so the bj_sleep() that paces this loop is exactly what such a program should use.

#include <banjo/log.h>
#include <banjo/main.h>
#include <banjo/system.h>
#include <banjo/time.h>
int main(int argc, char* argv[]) {
(void)argc; (void)argv;
if (!bj_begin(BJ_NO_SYSTEM, 0)) {
return 1;
}
// A stopwatch must be zero-initialised before use.
bj_stopwatch stopwatch = {0};
// Run for about 3 seconds, measuring the time around each iteration.
double elapsed = 0.0;
while (elapsed < 3.0) {
// Update the stopwatch once per iteration to record the current time.
// The first call starts the stopwatch.
bj_step_stopwatch(&stopwatch);
// Total time elapsed since the stopwatch started (first step call).
elapsed = bj_stopwatch_elapsed(&stopwatch);
// Delta time - time since the previous step. This is crucial for
// frame-independent movement and animation. For example:
// position += velocity * delay;
// ensures objects move at constant speed regardless of loop rate.
double delay = bj_stopwatch_delay(&stopwatch);
bj_trace("Elapsed: %.3lf s | Delay: %.3lf s", elapsed, delay);
bj_sleep(300);
}
bj_end();
return 0;
}
int main(int argc, char *argv[])
Definition audio_pcm.c:177
#define bj_trace(...)
Log a message using the BJ_LOG_TRACE level.
Definition log.h:113
bj_bool bj_begin(int systems, struct bj_error **error)
Initialises the system.
void bj_end(void)
De-initialises the system.
@ BJ_NO_SYSTEM
Definition system.h:79
void bj_sleep(int milliseconds)
Suspends the current thread for a specified duration.
double bj_stopwatch_delay(const struct bj_stopwatch *stopwatch)
Returns the time in seconds since the last step.
void bj_step_stopwatch(struct bj_stopwatch *stopwatch)
Records a step/checkpoint in time.
double bj_stopwatch_elapsed(const struct bj_stopwatch *stopwatch)
Returns the elapsed time in seconds since the stopwatch was reset.
Structure representing a simple stopwatch.
Definition time.h:150
Logging utility functions.
Portable main() replacement with platform-aware entry shim.
Header file for system interactions.
Header file for time manipulation utilities.