PHP Sub-Second Sleep

I needed to add a sleep to a PHP process, but I didn’t want to waste a whole second on each cycle. That’s usleep:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
        date_default_timezone_set('America/New_York');
 
        $t = microtime(true);
        $micro = sprintf("%06d",($t - floor($t)) * 1000000);
        $d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
 
        print $d->format("Y-m-d H:i:s.u") . "\n";                                                                      
        usleep(100000);
 
        $t = microtime(true);
        $micro = sprintf("%06d",($t - floor($t)) * 1000000);
        $d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
 
        print $d->format("Y-m-d H:i:s.u")  . "\n";                                                                     
        sleep(1);
        $t = microtime(true);
        $micro = sprintf("%06d",($t - floor($t)) * 1000000);
        $d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
 
        print $d->format("Y-m-d H:i:s.u")  . "\n";                                                                     
?>

Run the script, and you’ll see sub-second sleeps.

[tempuser@564240601ac2 /]# php testSleep.php
2020-07-09 14:06:20.641449
2020-07-09 14:06:20.741952
2020-07-09 14:06:21.742347

Leave a Reply

Your email address will not be published. Required fields are marked *