veandco / go-sdl2

SDL2 binding for Go
https://godoc.org/github.com/veandco/go-sdl2
BSD 3-Clause "New" or "Revised" License
2.2k stars 219 forks source link

Extremely High CPU Usage #346

Closed ghost closed 6 years ago

ghost commented 6 years ago

Just wondering whats going on here... On my razer blade stealth (dual core i7) running Arch Linux with Xorg and the following program, I am getting CPU usage of 25%..... super unusual for such a simple program.

package main

import "github.com/veandco/go-sdl2/sdl"

func main() {
    if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {
        panic(err)
    }
    defer sdl.Quit()

    window, err := sdl.CreateWindow("test", sdl.RENDERER_PRESENTVSYNC, sdl.WINDOWPOS_UNDEFINED,
        800, 600, sdl.WINDOW_SHOWN)
    if err != nil {
        panic(err)
    }
    defer window.Destroy()

    surface, err := window.GetSurface()
    if err != nil {
        panic(err)
    }
    surface.FillRect(nil, 0)

    rect := sdl.Rect{0, 0, 200, 200}
    surface.FillRect(&rect, 0xffff0000)
    window.UpdateSurface()

    running := true
    inx := 0
    for running {
        for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
            inx += 1
            println(inx)
            switch event.(type) {
            case *sdl.QuitEvent:
                println("Quit")
                running = false
                break
            }
        }
    }
}
veeableful commented 6 years ago

Hi @rucuriousyet, I believe it is because you are running a busy loop without letting the thread sleep. You can put an sdl.Delay(16) inside the loop at the end to make it not so busy.

ghost commented 6 years ago

Are you sure @veeableful? sdl.PollEvent blocks until an event is pushed in, so Im not sure why it would be going crazy over a loop.

ghost commented 6 years ago

oh never mind.. I see what's going on. You're right. Thanks for the help.