Skip to main content
gamedev.net
🔒 Locked

Limitting program CPU usage

Started by Striken 6 replies 1k views
Original Post
Striken
Striken
Hi all, I need a bit of advice; really simple question - for a program (*NOT* a game) that runs constantly:

int main() {
  bool done = false;
  while(!done) {
    //do stuff
  }
  return 0;
}
What is the best way to manage it's CPU usage? If I wanted to run a roughly *frame* a second, would Sleep(1000-x) (where x is the time in ms taken to process that frame) would that be sufficient for a high performace app? Thanks in advance.
Teach a programmer an answer, he can code for a day. Show a programmer the documentation, he can code for a lifetime.
Hodgman
Hodgman
Quote:
Original post by Striken
If I wanted to run a roughly *frame* a second, would Sleep(1000-x) (where x is the time in ms taken to process that frame) would that be sufficient for a high performace app?


I'm maintaining a rendering tool that does exactly what you just described.
But make sure to check that 1000-x isn't negative, in which case you don't have to sleep ;)
swiftcoder
swiftcoder
Sleep functions have very lousy accuracy in general (and especially on Windows), so you will want to sleep for a bit less than the full (1000 - x) you have calculated, say for instance (900 - x). Other than that, yes this approach works and is usually the simplest way to yield the CPU.
Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]
Striken
Striken
Thanks guys, I guess I should have put this in the beginners forum in hindsight :)
Teach a programmer an answer, he can code for a day. Show a programmer the documentation, he can code for a lifetime.
MJP
MJP
If you're using Win32 and you have a UI app, be careful not to Sleep for long periods of time. While your thread is sleeping the day away, nobody is processing your thread's messages so they could be building up. Either keep your Sleeps to a minimum (15ms or so), or use a function like MsgWaitForMultipleObjects that will wake you up if a message arrives.
iMalc
iMalc
Assuming this is a Windows program, use a standard Windows message loop with GetMessage etc, start a timer, and do the work upon receiving the WM_TIMER messages.
Striken
Striken
I'm building it in a win32 environment but I'll be porting it over to Solaris 10 / Linux (RH4). It's only a "console" app. Your concerns are noted :)
Teach a programmer an answer, he can code for a day. Show a programmer the documentation, he can code for a lifetime.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.