首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 高精度執行計時器類別實作與微秒級效能分析

     編輯:PHP 綜合知識

為何需要高精度計時

分析函式效能、SQL 查詢耗時、API 回應延遲時,microtime(true) 提供微秒級精度,遠優於秒級 time()。封裝為類別可方便多點計時、巢狀計時與報表輸出。

現代化 Timer 類別實作(PHP 7.4+)

<?php
declare(strict_types=1);

class HighPrecisionTimer
{
    private float $startTime = 0.0;
    private float $stopTime = 0.0;
    private array $laps = [];
    private string $label = '';

    public function __construct(string $label = '')
    {
        $this->label = $label;
    }

    public function start(): self
    {
        $this->startTime = microtime(true);
        return $this;
    }

    public function stop(): self
    {
        $this->stopTime = microtime(true);
        return $this;
    }

    public function lap(string $name = ''): self
    {
        $now = microtime(true);
        $this->laps[] = [
            'name' => $name ?: 'lap_' . count($this->laps),
            'time' => $now,
            'duration' => $now - ($this->laps[-1]['time'] ?? $this->startTime),
        ];
        return $this;
    }

    public function elapsed(): float
    {
        $end = $this->stopTime ?: microtime(true);
        return $end - $this->startTime;
    }

    public function getLaps(): array
    {
        return $this->laps;
    }

    public function __toString(): string
    {
        $total = $this->elapsed();
        $output = sprintf("[%s] 總耗時: %.6f 秒\n", $this->label ?: 'Timer', $total);
        foreach ($this->laps as $lap) {
            $output .= sprintf("  ├─ %s: %.6f 秒\n", $lap['name'], $lap['duration']);
        }
        return $output;
    }
}

使用範例

<?php
// 基本計時
$timer = new HighPrecisionTimer('API請求');
$timer->start();
// ... 業務邏輯 ...
usleep(150000); // 模擬 150ms 延遲
$timer->stop();
echo $timer; // 輸出格式化報表

// 多階段計時
$timer = new HighPrecisionTimer('訂單處理流程');
$timer->start();
$timer->lap('驗證參數');
validateInput();
$timer->lap('資料庫寫入');
saveToDb();
$timer->lap('發送通知');
sendNotification();
$timer->stop();

echo $timer;
/*
[訂單處理流程] 總耗時: 0.245123 秒
  ├─ 驗證參數: 0.012345 秒
  ├─ 資料庫寫入: 0.189012 秒
  ├─ 發送通知: 0.043766 秒
*/

進階應用:中介層自動計時

// Laravel / Slim / 自製框架中介層範例
$app->add(function ($request, $handler) {
    $timer = new HighPrecisionTimer('HTTP ' . $request->getMethod());
    $timer->start();
    $response = $handler->handle($request);
    $timer->stop();
    // 記錄慢請求
    if ($timer->elapsed() > 1.0) {
        error_log('Slow Request: ' . $timer);
    }
    $response->getHeaders()['X-Response-Time'] = $timer->elapsed();
    return $response;
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved