雖然專業工具(fio、CrystalDiskMark、dd)更精準,但在容器化、Serverless、共享主機等受限環境,無法安裝原生工具時,PHP 腳本能快速給出「應用層視角」的寫入效能參考,幫助排查上傳慢、日誌寫入阻塞等問題。
<?php
/**
* 磁碟寫入速度測試
* @param int $totalBytes 總寫入位元組(預設 1GB)
* @param int $chunkSize 每次寫入塊大小(預設 512KB)
* @param bool $sync 是否強制同步到磁碟(fsync)
*/
function diskWriteBenchmark(int $totalBytes = 1073741824, int $chunkSize = 524288, bool $sync = false): array
{
// 關閉時間限制
set_time_limit(0);
// 避免輸出緩衝干擾計時
@ob_end_clean();
$tempFile = sys_get_temp_dir() . '/disk_bench_' . uniqid() . '.tmp';
$buffer = random_bytes($chunkSize); // 使用隨機資料避免壓縮/去重優化影響結果
$fp = fopen($tempFile, 'wb');
if (!$fp) {
throw new RuntimeException("無法建立暫存檔:$tempFile");
}
$bytesWritten = 0;
$start = hrtime(true);
while ($bytesWritten < $totalBytes) {
$remaining = $totalBytes - $bytesWritten;
$writeSize = min($chunkSize, $remaining);
$written = fwrite($fp, $buffer, $writeSize);
if ($written === false) {
throw new RuntimeException('寫入失敗');
}
$bytesWritten += $written;
if ($sync) {
fsync($fp); // 強制刷新到物理磁碟
}
}
if (!$sync) {
fflush($fp); // 至少刷新 OS 快取
}
fclose($fp);
$elapsedNs = hrtime(true) - $start;
$elapsedSec = $elapsedNs / 1e9;
$speedMBps = ($totalBytes / 1024 / 1024) / $elapsedSec;
// 清理
@unlink($tempFile);
return [
'total_mb' => round($totalBytes / 1024 / 1024, 2),
'chunk_kb' => $chunkSize / 1024,
'sync_mode' => $sync,
'elapsed_sec' => round($elapsedSec, 3),
'speed_mbps' => round($speedMBps, 2),
'iops' => round($totalBytes / $chunkSize / $elapsedSec),
];
}
// 執行測試
try {
echo "=== 一般快取寫入(OS Buffered) ===\n";
print_r(diskWriteBenchmark());
echo "\n=== 同步寫入(fsync 每塊) ===\n";
print_r(diskWriteBenchmark(sync: true));
echo "\n=== 小塊 4KB 模擬資料庫頁寫入 ===\n";
print_r(diskWriteBenchmark(chunkSize: 4096));
} catch (Throwable $e) {
echo "錯誤:" . $e->getMessage();
}
?>
| 儲存類型 | Buffered 寫入 | fsync 寫入 | 4KB 隨機 IOPS |
|---|---|---|---|
| SATA SSD | 400-500 MB/s | 100-200 MB/s | 80K-100K |
| NVMe Gen3 | 2000-3000 MB/s | 800-1500 MB/s | 300K-500K |
| NVMe Gen4 | 5000-7000 MB/s | 2000-3000 MB/s | 800K-1M+ |
| 機械硬碟 7200rpm | 150-200 MB/s | 80-120 MB/s | 80-150 |
random_bytes() 產生隨機數成瓶頸,改用固定緩衝區重複寫入<?php
// 模擬日誌追加寫入(小塊、頻繁、fsync)
function simulateLogWrite(int $lines = 100000, int $lineBytes = 200): array
{
$tempFile = sys_get_temp_dir() . '/log_bench_' . uniqid() . '.log';
$fp = fopen($tempFile, 'ab');
$line = str_repeat('x', $lineBytes - 1) . "\n";
$start = hrtime(true);
for ($i = 0; $i < $lines; $i++) {
fwrite($fp, $line);
fsync($fp); // 模擬關鍵日誌同步
}
fclose($fp);
$elapsed = (hrtime(true) - $start) / 1e9;
@unlink($tempFile);
return ['lines' => $lines, 'elapsed_sec' => $elapsed, 'lines_per_sec' => round($lines / $elapsed)];
}
?>
sys_get_temp_dir() 所在分區有足夠空間--device-write-bps 限制 IO,測試會反映限制後速度PHP 磁碟基準測試雖不替代專業工具,但能在受限環境快速定位「應用層感知」的 IO 性能。關鍵在於:區分 Buffered 與 Sync 模式、選擇適當塊大小、排除 CPU 產生資料的干擾。定期在部署環境跑一次,建立基準線,異常時才能快速比對。