cp420
cp420

Reputation: 85

SDL_Renderer using 100% CPU and a gig of RAM to do nothing

I was making a game with SDL2, and shortly in the game was taking too much RAM to even close. I stripped down the code, and found that even this pointless, one file program uses 100% of my CPU and a gig of RAM.

#include "SDL.h"
#include "SDL_image.h"
#include <cassert>

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

SDL_Renderer* gRenderer;
SDL_Window* gWindow;

void init();
void close();

int main()
{
    init();
    SDL_Event e;
    bool quit;

    while( !quit )
    {
         while( SDL_PollEvent( &e ) != 0 )
         {
              if( e.type == SDL_QUIT )
                  quit = true;
         }
    }
    close();
}

void init()
{
    assert( SDL_Init( SDL_INIT_EVERYTHING ) >= 0 );
    gWindow = SDL_CreateWindow( "Space", SDL_WINDOWPOS_UNDEFINED,
                   SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
                   SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
    assert( gWindow );

    gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED );
    assert( gRenderer );

    int imgFlags = IMG_INIT_PNG;
    assert( IMG_Init( imgFlags ) & imgFlags );

    SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
}

void close()
{
    SDL_DestroyRenderer( gRenderer );
    SDL_DestroyWindow( gWindow );

    IMG_Quit();
    SDL_Quit();
}

Upvotes: 3

Views: 1773

Answers (3)

Paingouin
Paingouin

Reputation: 11

Using assert can use a LOT of RAM, maybe you should consider not using these. Try just a simple if to test your initializes.

Edit: It's seem that the RAM problem didn't came from that. Sorry for the bad answer

Upvotes: 0

user3684240
user3684240

Reputation: 1580

As Ivan already mentioned, you should try limiting the FPS of your program. One way to do this is to use SDL_GetTicks to measure the duration and then use SDL_Delay if it is fast enough. That way, a modern computer will sleep most of the time while a bad one will still get good framerates:

while(running) {
  auto time = SDL_GetTicks();
  // Rendering and event handling
  if ((SDL_GetTicks() - time) < 10) {
    SDL_Delay(10);
  }
}

You should play a little with the numbers (10 and 10 in the example) in order to see how many FPS your program needs.

Upvotes: 2

Ivan Rubinson
Ivan Rubinson

Reputation: 3329

You're running to program as fast as possible, therefore it's using all resources it can get.

Try limiting the FPS.

Upvotes: 2

Related Questions