CakeFest 2024: The Official CakePHP Conference

hrtime

(PHP 7 >= 7.3.0, PHP 8)

hrtime获取系统的高精度时间

说明

hrtime(bool $as_number = false): array|int|float|false

从任意时间点开始统计,返回系统的高精度时间(high resolution time)。 获取的时间戳为单调时间,无法被用户调整。

参数

as_number

array 还是数字返回高精度时间。

返回值

参数 as_number 为 false 时,返回的整型数组格式为 [seconds, nanoseconds]。否则会以 int (64 位平台)或 float (32 位平台)返回奈秒(nanoseconds)。失败时返回 false

示例

示例 #1 hrtime() 的用法

<?php
echo hrtime(true), PHP_EOL;
print_r(hrtime());
?>

以上示例的输出类似于:

10444739687370679
Array
(
    [0] => 10444739
    [1] => 687464812
)

参见

add a note

User Contributed Notes 1 note

up
62
SenseiSimple
5 years ago
This function is particularly necessary on VMs running on KVM, XEN (openstack, AWS EC2, etc) when timing execution times.

On these platforms which lack vDSO the common method of using time() or microtime() can dramatically increase CPU/execution time due to the context switching from userland to kernel when running the `gettimeofday()` system call.

The common pattern is:
<?php
$time
= -microtime(true);
sleep(5);
$end = sprintf('%f', $time += microtime(true));
?>

Substituted as:
<?php
$start
=hrtime(true);
sleep(5);
$end=hrtime(true);
$eta=$end-$start;

echo
$eta/1e+6; //nanoseconds to milliseconds
//5000.362419

//OR simply

$eta=-hrtime(true);
sleep(5);
$eta+=hrtime(true);

echo
$eta/1e+6; //nanoseconds to milliseconds
//5000.088229
?>

There is also the new StopWatch class http://php.net/manual/en/class.hrtime-stopwatch.php
To Top