在執行於 KVM、XEN (OpenStack、AWS EC2 等) 的虛擬機器上計算執行時間時,此函式尤其必要。
在這些缺乏 vDSO 的平台上,使用 time() 或 microtime() 的常見方法會因為執行 `gettimeofday()` 系統呼叫時從使用者空間到核心空間的上下文切換而大幅增加 CPU/執行時間。
常見的模式是
<?php
$time = -microtime(true);
sleep(5);
$end = sprintf('%f', $time += microtime(true));
?>
替換為
<?php
$start=hrtime(true);
sleep(5);
$end=hrtime(true);
$eta=$end-$start;
echo $eta/1e+6; // 將奈秒轉換為毫秒
//5000.362419
//或者更簡潔的寫法
$eta=-hrtime(true);
sleep(5);
$eta+=hrtime(true);
echo $eta/1e+6; // 將奈秒轉換為毫秒
//5000.088229
?>
還有新的 StopWatch 類別 https://php.dev.org.tw/manual/en/class.hrtime-stopwatch.php