Skip to content

Fix CPU usage when using vsync #90

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions nico/backends/sdl2.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1876,15 +1876,18 @@ proc run*() =
if configInitialised:
step()

if not vsyncEnabled:
# calculate how long we should sleep for to reduce cpu usage, if we have vsync this will do it for us
let frameEndTime = getPerformanceCounter()
let frameTime = ((frameEndTime - frameStartTime)*1000).float / getPerformanceFrequency().float
let targetFrameTime = 1000.0 / frameRate.float
let sleepTime = targetFrameTime - frameTime
#echo "frame time: ", frameTime, " target: ", targetFrameTime, " sleep time: ", sleepTime
if sleepTime > 0f:
# calculate how long we should sleep for to reduce cpu usage
let frameEndTime = getPerformanceCounter()
let frameTime = ((frameEndTime - frameStartTime)*1000).float / getPerformanceFrequency().float
let targetFrameTime = 1000.0 / frameRate.float
let sleepTime = targetFrameTime - frameTime
# echo "frame time: ", frameTime, " target: ", targetFrameTime, " sleep time: ", sleepTime
if sleepTime >= 1.0:
if vsyncEnabled:
delay(1) # if we have vsync this will wait for us, but delay(1) is necessary to keep CPU usage down
else:
delay(sleepTime.uint32)

sdl.quit()

when defined(emscripten):
Expand Down