PHP 8.3.4 Released!

hrtime

(PHP 7 >= 7.3.0, PHP 8)

hrtimeシステムの高精度な時刻を取得する

説明

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

任意のタイミングから計測したシステムの高精度な時刻を取得します。 返されたタイムスタンプは単調であり、調整できません。

パラメータ

as_number

高精度の時刻を array で取得するか、数値で取得するかを指定します。

戻り値

as_numberfalse の場合は、 [秒, ナノ秒] の形式で数値の配列を返します。 true の場合、ナノ秒を (64ビットプラットフォームの場合) int または float (32ビットプラットフォームの場合) として返します。 失敗した場合は 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