Jimit
Jimit

Reputation: 2259

How usleep unloads the CPU?

Can anyone explain me how usleep or sleep helps to unload the CPU.
I have written sample code as below.

while (1) // check if the data file has been modified 
{
  usleep(10000); // sleep 10ms to unload the CPU**
  clearstatcache();
  $currentmodif = filemtime($filename);
}

Upvotes: 1

Views: 195

Answers (3)

Ariel
Ariel

Reputation: 26753

Instead of doing that use this: http://www.php.net/inotify

Be sure to use stream_set_blocking() to turn on blocking mode - that way you won't use any cpu at all while waiting.

Upvotes: 0

user680786
user680786

Reputation:

Imagine that you have to wait 8 hours for some event.
You have 2 choices:

  • look at watches each second
  • set alarm after 8 hours and go to sleep or do something else

So sleep() and usleep() is second variant.

Upvotes: 0

Johan
Johan

Reputation: 76567

If you run usleep() the CPU will not spend time waiting around.
Instead it will set a timer and use the extra time on other threads/programs.

If you write code that does a lot of work to burn away the CPU time, the CPU will be working hard at that, ignoring other tasks, because it thinks it is doing useful work.
If you use usleep the CPU (actually the OS) knows there is nothing useful to be done and will prioritize other work.

Upvotes: 2

Related Questions