Search code examples
c++windowsdllag

SDL Lag / Super slow (SDL 2.0.14)


i have a game loop which measures the ms it takes to finish. before entering the loop i call a "Init" function which looks like this:

void screen::Init()
{
    if(SDL_Init(SDL_INIT_EVERYTHING) == 0)
    {
        m_window = SDL_CreateWindow("TITLE", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH*SIZE, HEIGHT*SIZE, NULL);

        m_renderer = SDL_CreateRenderer(m_window, -1, NULL);
        if(m_renderer)
            SDL_SetRenderDrawColor(m_renderer, 0,0,0,0);

        m_Texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, WIDTH, HEIGHT);

    }
}

The thing is that when i call the function one execution of the loop takes 70 to 90 ms! if i leave the "init" function call out (so no window shown) its only 2-4 ms.

The loop does nothing other than calling one function which looks like the following:

void screen::handleEvents()
{
    SDL_PollEvent(&m_event);
    switch(m_event.type)
    {
        case SDL_QUIT:
            screen->Clean();
            break;
        default:
            break;
    }
}

leaving the handleEvents function out results in 0-2ms, but the window crashes the moment i click on it.

not sure what im doing wrong but im pretty sure it shouldnt slow down to ~10 FPS lol

Here is the rest of the code:

#define SIZE 5
#define WIDTH 150
#define HEIGHT 150

int main(int argc, char* argv[])
{
    screen* screen = new class screen;

    screen->Init();

    while(screen->running)
    {
        screen->execute();
    }
    return 0;
}
void screen::execute()
{
    if(currline == 1 && Time == 0)
        start = SDL_GetTicks();

    if(Time > 0)
        Time--;
    else
        counter();

    handleEvents();

    if(currline == 151 && Time == 0)
    {
        end = SDL_GetTicks();
        printf("s: %8d e: %8d r: %d\n", start, end, end-start);
    }
}
void screen::counter()
{
    if(currline > 150)
        currline = 255;

    currline++;

    Time = 500;
};

Solution

  • okay, found out why it was lagging:

    i was calling handleevent everytime it executed a loop (which is a couple thousand times per second) instead of doing it inside this if statement:

    if(currline == 151 && Time == 0)
        {
            end = SDL_GetTicks();
            printf("s: %8d e: %8d r: %d\n", start, end, end-start);
        }
    

    the if statement is there to "restrict" the whole thing to a certain framerate :)

    usually you would do a sleep at the end of the whole loop to get your 60 executions per second, but since i did it inside this if statment i had to put the function-call in there.