r/learnprogramming • u/Extra-Neighborhood12 • 1d ago
How could i decrement a value in a variable, x times over a certain period of time in C?
I'm creating an emulator of CHIP-8 in C following the Tobias' guide and I should decrement the value of delay and sound timers 60 times per seconds but i don't know how to do this. Maybe could be something in SDL2 but i want to implement this feature independently by this library so i can easily import this emulator on other devices changing just the graphics and input management.
2
Upvotes
2
u/StatsDota_Dmitrii 1d ago
not a real programmer lol but you dont need async for this. in your main loop just read the time (clock_gettime with CLOCK_MONOTONIC on linux, its plain C, no sdl) and every time 1/60 sec passed decrement both timers by 1, keep the leftover time so it doesnt drift. same loop can run the cpu at like 500-700 instructions per sec
2
u/Big_Inflation864 1d ago
The usual way is to not count time with a loop at all, but to compare against a real clock once per frame. Keep a timestamp of the last timer tick, and each iteration of your main loop get the current time (clock_gettime with CLOCK_MONOTONIC, or just keep an accumulator of elapsed time per frame). While the accumulated time is at least 1/60 of a second (about 16.67 ms), decrement delay and sound timers if they are above zero and subtract 16.67 ms from the accumulator. That keeps the timers at 60 Hz no matter how fast your CPU loop runs, and your core stays free of SDL. The platform layer just passes in the elapsed time, or you expose a function like cpu_tick_timers() that the frontend calls 60 times a second.
2
u/Chad_Frost 1d ago
Look into delta time. It's a standard way of calculating time in video games. It gives you how much time has passed since the last frame, so you can subtract delta time from the timer and it'll decrement by a determined amount regardless of how long each cycle takes.
2
u/jjangg96 1d ago
one way that keeps the core portable is to not put the clock in the emulator at all. expose something like chip8_tick_timers() that does if (delay > 0) delay--; if (sound > 0) sound--; and let each frontend call it 60 times a second.
on the frontend side use a monotonic clock (clock_gettime(CLOCK_MONOTONIC) on posix, QueryPerformanceCounter on windows) and an accumulator. each loop add the time since the last iteration, then while (acc >= 1.0/60) { tick(); acc -= 1.0/60; }. subtracting instead of resetting to zero is what keeps it from drifting.
i wouldn't sleep(16ms) for this either, sleeps overshoot a bit every time and it adds up. the accumulator takes care of that.
1
u/jeffcgroves 1d ago
Asynchronous programming maybe something to google.