$start = microtime(true);
// SQL 查詢
$end = microtime(true);
$diff = $end - $start; // 偶爾出現負數
PHP float(IEEE 754 雙精度)無法精確表示某些十進制小數(如 0.1、0.7)。兩個極接近的浮點數相減,因二進制表示誤差導致結果為負。
// 經典案例
floor((0.1 + 0.7) * 10) // 得 7 而非 8
// 內部實際為 7.99999999999999...
$start = microtime(true);
// 執行查詢
$end = microtime(true);
$diff = $end - $start; // 直接相減,精度足夠
microtime(true) 回傳含微秒的浮點秒數,避免字串拆解組合誤差。
$start = hrtime(true); // 納秒陣列 [秒, 納秒] 或布林 true 回傳總納秒
// 執行查詢
$end = hrtime(true);
$diff_ns = $end - $start;
$diff_ms = $diff_ns / 1_000_000; // 毫秒
$diff_sec = $diff_ns / 1_000_000_000;
$start = microtime(true);
$end = microtime(true);
$diff = bcsub($end, $start, 6); // 保留 6 位小數
microtime(true) 簡單且精度足夠(微秒級)。xhprof、Blackfire、Tideways 專業工具。== 比較兩個 float,用 abs($a - $b) < 0.000001。SHOW PROFILE 或 EXPLAIN ANALYZE 取得精確執行時間。