In high-precision tasks or time-sensitive PHP applications, ordinary sleep() or usleep() often fail to meet the nanosecond delay control requirements. sleep() can only be accurate to seconds. Although usleep() supports microseconds, it is still impossible to achieve stable high-precision control due to PHP's own scheduling mechanism and system accuracy limitations.
To solve this problem, the time_nanosleep() function provides a more refined way of delay control. This article will introduce how to combine microtime(true) and time_nanosleep() to achieve precise delay control.
time_nanosleep() is a function provided by PHP for nanosecond-level delay. Its function prototype is as follows:
bool time_nanosleep(int $seconds, int $nanoseconds)
It allows you to specify a combination of "seconds" and "nanoseconds" to pause script running. For example, if you want to delay by 1.5 milliseconds (i.e. 1500000 nanoseconds), you can use the following method:
time_nanosleep(0, 1500000);
Note: The behavior of time_nanosleep() is still affected by system clock accuracy and PHP implementation, and the true accuracy may be slightly biased. But in most applications, it is more stable than usleep() .
Sometimes we not only need to delay fixed time, but also want to ensure that the code is precisely controlled within a period of time from a certain point to the end of a certain point. At this time, microtime(true) is very useful, it returns the microsecond timestamp since the Unix epoch, with higher accuracy.
The following is an example of delay control implemented using time_nanosleep() and microtime(true) combination:
<?php
// Target delay time(In seconds)
$targetDelay = 0.005; // 5 millisecond
$start = microtime(true);
// Simulate performing certain operations
for ($i = 0; $i < 1000; $i++) {
// Assume that this cycle consumes some time
}
// Calculate the time consumed
$elapsed = microtime(true) - $start;
// Time required for additional delay
$remainingDelay = $targetDelay - $elapsed;
if ($remainingDelay > 0) {
// Split the remaining time into seconds and nanoseconds
$seconds = (int)$remainingDelay;
$nanoseconds = (int)(($remainingDelay - $seconds) * 1e9);
// Accurate delay
time_nanosleep($seconds, $nanoseconds);
}
// Total time-consuming check
$totalTime = microtime(true) - $start;
echo "Total time consumption: " . round($totalTime * 1000, 3) . " millisecond\n";
Control sampling intervals in real-time acquisition system
Speed limit download/upload function (such as limiting the frequency of access to a certain URL)
Simulate network delays when testing certain interface response behavior
For example, when implementing a speed limit API requester:
<?php
$urls = [
"https://gitbox.net/api/data/1",
"https://gitbox.net/api/data/2",
"https://gitbox.net/api/data/3"
];
$interval = 0.2; // Every 200 millisecond请求一次
foreach ($urls as $url) {
$start = microtime(true);
// Simulation request
file_get_contents($url);
$elapsed = microtime(true) - $start;
$remaining = $interval - $elapsed;
if ($remaining > 0) {
time_nanosleep(0, (int)($remaining * 1e9));
}
}
In this way, we can control the interval between each request more accurately, avoid putting pressure on the target server, or meet the rhythmic needs of our own applications.
time_nanosleep() is not a "hard real-time" in real-time operating systems and cannot guarantee 100% accuracy, but it is sufficient for use in non-critical occasions.
Some platforms or PHP compiled versions may not support time_nanosleep() . It is recommended to confirm whether the function is available before use.
If more stable timing accuracy is required, other languages (such as C) or system-level support may need to be considered.
Using time_nanosleep() with microtime(true) can achieve more precise delay control than usleep() in PHP, which is suitable for scenarios with high requirements for time control. Although it is still limited by system scheduling and PHP implementation details, it provides sufficient precision and flexibility in most applications and is an important tool for refined latency control.