Reputation: 2259
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
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
Reputation:
Imagine that you have to wait 8 hours for some event.
You have 2 choices:
So sleep()
and usleep()
is second variant.
Upvotes: 0
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