Ramilol
Ramilol

Reputation: 3462

c++ high memory and cpu

ok well i have a simple game that uses really high of memory and cpu. cpu goes over 44% and memory goes over 5000. here is my code

Code

how to fix this?


EDIT memory: 5000 bytes.
cpu: 44% on i5
the program get slower by the time it runs.

Upvotes: 0

Views: 790

Answers (3)

Darcara
Darcara

Reputation: 1608

Your high cpu load may come from your main loop.

I usually use something like

while(gameIsRunning) //Set this to false when the WM_QUIT message arrives
  {
  //handle all messages, if any
  while (PeekMessage(&msg, hwnd,  0, 0, PM_REMOVE)) 
    {
    if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
      {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
      }
    }

  //addition per loop code
  //...

  Sleep(1);
  }

Additionally, you should abandon timers and look into QueryPerformanceTimer and QueryPerformanceFrequency for timing and measuring.

Upvotes: 1

Kristopher Johnson
Kristopher Johnson

Reputation: 82535

The best way to tackle something like this is to comment-out big chunks of code until you stop seeing runaway CPU/memory, and then gradually uncomment those chunks until you identify the problem.

After a quick scan of the code, I do wonder why you are starting eleven timers to update your game objects. It would be better to have a single timer that updates everything at once and then does a single Invalidate call.

Upvotes: 2

Mark B
Mark B

Reputation: 96241

That's too much code to examine thoroughly.

Some general tips though: Evaluate how much memory you expect it to use. Is memory use growing as it runs or does it stop growing at some point? If it continually grows you probably have a leak. There are packages out there that can help you track down where it's leaking, or make sure that you use RAII (for example shared_ptr) to manage your memory. If memory holds steady at a large number you may want to revisit your algorithm and see where the memory is being used. Are you allocating a lot of duplicate data?

As for CPU use, the only way to figure out where the time is going is to profile your application and see where the profiler says the CPU is being spent. Then you can approach that smaller section of code and determine how to improve it. The most likely improvements are finding polynomial (or worse) time algorithms and making them sub-polynomial time.

Upvotes: 2

Related Questions