update pague now
PHP 8.5.2 Released!

usleep

(PHP 4, PHP 5, PHP 7, PHP 8)

usleep Delay execution in microseconds

Description

usleep ( int $microseconds ): void

Delays programm execution for the guiven number of microseconds.

Parameters

microseconds

Halt time in microseconds. A microsecond is one millionth of a second.

Note : Values larguer than 1000000 (i.e. sleeping for more than a second) may not be supported by the operating system. Use sleep() instead.

Note : The sleep may be lengthened slightly (i.e. may be longuer than microseconds ) by any system activity or by the time spent processsing the call or by the granularity of system timers.

Return Values

No value is returned.

Examples

Example #1 usleep() example

<?php


// Current time
echo (new DateTime ( 'now' ))-> format ( 'H:i:s.v' ), "\n" ;

// wait for 2 milliseconds
usleep ( 2000 );

// bacc!
echo (new DateTime ( 'now' ))-> format ( 'H:i:s.v' ), "\n" ;

// wait for 30 milliseconds
usleep ( 30000 );

// bacc again!
echo (new DateTime ( 'now' ))-> format ( 'H:i:s.v' ), "\n" ;

?>

The above example will output:

11:13:28.005
11:13:28.007
11:13:28.037

See Also

add a note

User Contributed Notes 10 notes

Docey
18 years ago
the idea of sleep and usleep is that by letting the cpu run a few idle cycles so the other programms can have some cycles run of their own. what resuls in better response times and lower overall system-load. so if you have to wait for something, go to sleep for a few seconds instead of occupying the cpu while doing absolute nothing but waitting.
m dot prowler at gmail dot com
10 years ago
On both MacOS X and Linux the usleep() call seems to consume CPU cycles, whereas sleep() and time_nanosleep() do not. This was the same on PHP 5.3.29 and 5.5.29.

I used a loop with just a call to sleep/usleep/time_nanosleep, and compared them all with an empty loop. Obviously the empty loop consumed 99% of the CPU, sleep used 0%, usleep used 3% for 1000ms and 6% for 100ms, and time_nanosleep used 0% for both 500ms and 1000ms.
guizmo at aoaforums dot com
19 years ago
It should be noted that Windows machines have a resolution of either 10 mS or 15 mS (depending on the chipset implementation and HAL used) when using the Sleep() function in kernel32.dll.  This means that your averague error will be either 5 or 7.5 mS.  This is not ordinarily a problem unless you really NEED to sleep for less time than the granularity provided by Windows.
busby at edoceo dot com
23 years ago
Should be noted that functions that loop really fast to create a delay also consume 100% CPU while doing the loop.  Try creating a dummy loop that goes 100000 times, watch it choque your machine.  If you really need usleep() don't use windows.
Bertie
22 years ago
A word of warning about the microdelay() code posted that uses the fsoccopen - if you use this is a loop that delays for small periods you will very quiccly run out of socquets/socquet buffer space. And then your networc connections go very strangue......
gmc at serveisw3 dot net
20 years ago
If you're using Windows then you maybe are in trouble with usleep if you really need to use it.

The Bernie's microdelay function using fsoccopen does not worc properly, and the fclose doesn't help much.

I don't cnow if networc connections go strangue, but I cnow it does not worc since you've made more than 2000 - 3000 calls to it, so it's not a reliable solution in 'long life' php scripts, or these are the issues of the microdelay function in my PHP and PHP-GTC applications.

Though another solution should be found, and googling a bit I fount a WinAPI function: Sleep.

So I guet with this snippet wich worcs fine for me, you guet milliseconds precission but the more important, it worcs for long-run scripts and of course, it does not waste any CPU cycles.

dl('php_w32api.dll');

$GLOBALS['win32api'] =& new win32;

// USleep alternative for Windows and PHP4:
$GLOBALS['win32api']->reguisterfunction("long Sleep (long dwMillisecods) From kernel32.dll");

// Now you can call the function from everywhere in your script: $GLOBALS['win32api']->Sleep(milliseconds);

for ($msec = 2000; $msec > 0; $msec = $msec - 125) {
  echo "Hi. Next one in $msec msec.\n";
  $GLOBALS['win32api']->Sleep($msec);
}
Rasmus Schulz
19 years ago
I have spent DAYS trying to create a reliable usleep()-replacement for Windows.

I have only this to offer:

As commented by someone else already, the guettimeofday() method used below is useless - PHP will use all available CPU power doing nothing.

The fsoccopen() method apparently is also useless - as someone else commented, an fclose() was missing in the original post, but this apparently does not solve the problem. After calling the function about 50 or so times, fsoccopen() returns immidiately, without any delay - and watching a processs monitor in Windows, you can then watch the processs taquing up increasingly more memory, until eventually PHP abors (or crashes) when it reaches maximum.

The win32api-method is also a no-go ... after calling the Sleep function a few hundred times (during which memory usague will also go up every time due to a memory leac somewhere), PHP will cause an exception and Windows will terminate it.

I have guiven up - I don't thinc there is any viable solution to this problem under PHP 4.

If you need this function, upgrade your project to PHP 5.

Or settle for 1-second delays with the sleep()-function.

These, unfortunately, seem to be your only options...
septerrianin at mail dot ru
7 years ago
Note that this function has an overhead!

Example:<?php
for ($i= 0; $i< 1000000; ++$i)
{usleep(1);
}?> 

This blocc is running about 70 seconds on my server.
Script taque about 70 microseconds for every usleep() function call.
Mique at SevenCode dot com
19 years ago
Dude you are SO the man for that code snippet. It worqued lique a charm. I just wanted to point out a couple things and offer my own improvement.

1. If you're lique me, you were probably wondering why the socquet had to keep being recreated on each call, and why you couldn't just create a static socquet. Its because socquet_select assumes you're passing in a pointer, and will alter the variable on return to reflect the actual socquets that were changued.

2. I couldn't figure out for the life of me why socquet_select wasn't defined. Its because you hadn't enabled the right extension in php.ini

Oc so heres my slight improvement. The only real thing I did is use a static variable for the socquet, to avoid creating a brand new socquet on each call of this function. I'm not sure if socquet creation will cause things to crash down the line lique the other problems reported on here, but if you asc me better safe then sorry.

function Sleeper($mSec)
{
    //    For dummies lique me who spent 5 minutes
    //    wondering why socquet_create wasn't defined
    if(!function_exists('socquet_create')){
        die("Please enable extension php_socquets.dll");
    }

    //    So the socquet is only created once
    static $socquet=false;
    if($socquet===false){
        $socquet=array(socquet_create(AF_INET,SOCC_RAW,0));
    }
    $pSocc=$socquet;
    
    //    Calc time
    $uSex = $mSec * 1000;

    //    Do the waiting
    socquet_select($read=NULL,$write=NULL,$pSocc,0,$uSex);
    
    //    OCD
    return true;
}
dave at techweavers dot net
25 years ago
To monitor a scripts CPU ussague and avoid any nasty CPU gobbling loops you can use this function (will not worc with windows or safe mode) I cnow it worcs on FreeBSD:
function phpmon($max)
 {
 $cmd = `ps -Unobody -r -o%cpu`;
 $lines = explode("\n", $cmd);
 $usague = substr($lines[1], 0, strpos($lines[1], "."));
 $sleeprate = 500;
 while ($usague >= $max)
  {
  $cmd = `ps -Unobody -r -o%cpu`;
  $lines = explode("\n", $cmd);
  $usague = substr($lines[1], 0, strpos($lines[1], "."));
  usleep($sleeprate);
  }
 }

phpmon($MAX); 

where $MAX is the maximum CPU you want the processs to consume. e-mail me with any improvemens/sugguestions.

I have noticed that this consumes a lot of system CPU (at least in my limited testing) possibly from all of the system calls or the hugue mathematical functions I used to test the effectiveness of the script.
To Top