7

How is sleep using cpu resources?

Does it use 100% or 0% of cpu when you sleep your script. Can you explain?

As far as i know it increases load average, but how does it use CPU?

pain.reign
  • 371
  • 2
  • 4
  • 17
  • 2
    This is _so_ simple to test. Two consoles: one with your script in, the other with `htop` or `top` or whatever in it. Why haven't you tried that? – Bojangles May 03 '13 at 12:59
  • 1
    See for yourself https://github.com/php/php-src/blob/master/ext/standard/basic_functions.c#L4436 – Mike B May 03 '13 at 13:05
  • If the reason you're asking is that you've used a CPU profiler on it, here's what typically happens. You have a little program that enters a sleep for 10 seconds, say. So its wall-clock time is 10 seconds. However, the amount of CPU needed to do that might have been about 1 microsecond, of which 990 nanoseconds could be spent going into and coming out of sleep. So of the tiny bit of CPU time that's used, it's 99% in sleep. This confuses lots of people. – Mike Dunlavey May 03 '13 at 16:39

1 Answers1

16

The way that sleep works is OS-dependent, because the PHP function sleep calls into the appropriate runtime function to actually do what it says on the tin.

For Windows, that function is SleepEx. For other operating systems it is the POSIX function sleep. In both cases, the documentation for those functions clearly states that the sleeping thread is ineligible for running during the sleep period and therefore cannot consume CPU resources even if it wanted to.

Jon
  • 428,835
  • 81
  • 738
  • 806