1

I am trying to learn the ob_start, ob_flush function and I found this code on internet

if (ob_get_level() == 0) ob_start();
for($i=0;$i<1000;$i++)
{
    echo "$i<br />";

    ob_flush();
    flush();
    usleep(30000);
        // sleep(0.03);
}

I am trying to change the usleep() function which is use with microseconds to sleep (seconds) but it doesn't work as the usleep().

Is there something wrong or difference between sleep() and usleep()?

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
Shin622
  • 645
  • 3
  • 7
  • 22
  • I have tried your code and it works right away. It nicely draws the numbers 0-999 on the screen in 3000ms intervals. – davidkonrad Oct 31 '14 at 11:09
  • This question is whack. OP knows the difference yet he still wishes to use fractions with `sleep()` (which won't work). Just use `usleep()`. That's what it was made for. – Alternatex Oct 31 '14 at 11:15
  • @davidkonrad and Gerald Schneider were right, sleep() only accept integer – Shin622 Oct 31 '14 at 15:24

3 Answers3

1

The difference between sleep is sleep Delays the program execution for the given number of seconds and usleep Delays program execution for the given number of micro seconds.

sanu
  • 548
  • 7
  • 15
1

You can't use fractions as a parameter for sleep()

sleep(0.03);

Here 0.03 will be cast into an integer

sleep(0);

So PHP will sleep for 0 seconds.

If you want to sleep for fractions of seconds, you have to use usleep() or time_nanosleep().

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
1

I think I have figured out an answer to what you are confused about :

sleep(0.03) does not work because it needs an integer. sleep(0.03) is interpreted as sleep(0).

Thats why there also is the function usleep() which provides sleep() in milliseconds, eg usleep(3000). And why there also is a third sleep function, time_nanosleep() which provides a mix of seconds and nanoseconds, even higher resolution.

I guess the three different functions is a result how the functions is built - demanding integers - and because the value of the largest integer is platform dependent. In 32bit the highest integer is 2147483647. In 64bit, the highest integer is 9223372036854775807.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265