Here is a quote from a textbook I’m reading at the moment:
“That is, whenever a thread needs to
execute a loop with a lot of
iterations, it is good practice to put
a sleep() in each iteration
– Event short sleep times, such as 5 milliseconds, can reduce the overall
CPU usage of the application from
100% to > 1%”
It’s a good practice, I believe, but; doesn’t scheduler does exactly that – A bit of time to thread1; suspend thread1; A bit of time to thread2…etc. I can’t grasp such drop rate, anyone willing to enlighten me?
You see this a lot in programs that update the display of something. It’s called Busy Waiting, and that’s bad.
If you have a loop that does something like this
You’re going to chew up your CPU when you really don’t need to. Do you need to render it, over and over and over, 100000+ times a second? No, you really only need about 30 frames a second.
This will limit you to a little under 100 frames per second, and you’ll end up with a much better performance.
You don’t always want this for processor intensive background threads, as you want them to have priority. That being said, if your background takes all the CPU, how will you process further input (like, I don’t know, a CANCEL button because you didn’t mean to start that intensive, hours-long calculation?)
So adding a small sleep to your threads CAN BE a very good decision.