fwrite() 連續寫入固定大小緩衝區 (預設 512 Bytes) 至檔案,累積至目標總量 (預設 1 GB)。time() 記錄開始/結束 Unix 時間戳 (秒級精度),計算耗時與平均寫入速率。<?php
/**
* Disk Write Speed Benchmark for PHP CLI
* Usage: php disk_write_benchmark.php [target_file] [total_bytes] [buffer_size]
* Example: php disk_write_benchmark.php /mnt/test/bench.tmp 1073741824 65536
*/
// 參數預設值
$targetFile = $argv[1] ?? './temp_write_test.tmp';
$totalBytes = isset($argv[2]) ? (int)$argv[2] : 1_073_741_824; // 1 GiB
$bufferSize = isset($argv[3]) ? (int)$argv[3] : 65_536; // 64 KiB buffer
// 移除執行時間限制
set_time_limit(0);
// 預先配置緩衝區字串 (避免迴圈內重複分配記憶體)
$buffer = str_repeat('x', $bufferSize);
echo "=== Disk Write Benchmark ===\n";
echo "Target file : {$targetFile}\n";
echo "Total size : " . formatBytes($totalBytes) . " ({$totalBytes} bytes)\n";
echo "Buffer size : " . formatBytes($bufferSize) . "\n";
echo "PHP version : " . PHP_VERSION . "\n";
echo "OS : " . PHP_OS . "\n";
echo "---------------------------\n";
// 開啟檔案:wb = 二進位寫入、截斷現有內容、不轉換換行
$fp = @fopen($targetFile, 'wb');
if (!$fp) {
die("ERROR: Cannot open {$targetFile} for writing. Check permissions & disk space.\n");
}
// 可選:關閉 PHP 緩衝,直接呼叫系統 write(),減少使用者空間複製
// stream_set_write_buffer($fp, 0); // 0 = unbuffered
$bytesWritten = 0;
$startTime = microtime(true); // 微秒級計時
while ($bytesWritten < $totalBytes) {
$remaining = $totalBytes - $bytesWritten;
$writeLen = ($remaining < $bufferSize) ? $remaining : $bufferSize;
$written = fwrite($fp, $buffer, $writeLen);
if ($written === false || $written === 0) {
die("\nERROR: fwrite() failed at {$bytesWritten} bytes. Disk full or I/O error.\n");
}
$bytesWritten += $written;
// 簡易進度顯示 (每 10% 輸出一次)
if ($bytesWritten % (int)($totalBytes / 10) < $bufferSize) {
$pct = round(($bytesWritten / $totalBytes) * 100);
echo "\rProgress: {$pct}% ({$bytesWritten} / {$totalBytes})";
}
}
$endTime = microtime(true);
fclose($fp);
$elapsed = $endTime - $startTime; // 秒 (浮點數)
$speedBps = $totalBytes / $elapsed; // Bytes/sec
$speedMBps = $speedBps / 1_048_576; // MiB/s (2^20)
$speedMbps = $speedBps * 8 / 1_000_000; // Mbit/s (10^6)
echo "\n---------------------------\n";
echo "Elapsed time : " . number_format($elapsed, 3) . " sec\n";
echo "Written : " . formatBytes($bytesWritten) . "\n";
echo "Avg write speed: " . number_format($speedMBps, 2) . " MiB/s (MB/s)\n";
echo " : " . number_format($speedMbps, 2) . " Mbit/s (Mbps)\n";
echo " : " . number_format($speedBps / 1_073_741_824, 2) . " GiB/s\n";
// 清理測試檔案 (可選,註解保留供事後檢查)
// unlink($targetFile);
// echo "Test file removed.\n";
function formatBytes(int $bytes, int $precision = 2): string {
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
$exp = $bytes > 0 ? floor(log($bytes, 1024)) : 0;
return round($bytes / (1024 ** $exp), $precision) . ' ' . $units[$exp];
}
?>
$ php disk_write_benchmark.php /tmp/bench.tmp 1073741824 65536
=== Disk Write Benchmark ===
Target file : /tmp/bench.tmp
Total size : 1.00 GiB (1073741824 bytes)
Buffer size : 64.00 KiB
PHP version : 8.2.12
OS : Linux
---------------------------
Progress: 100% (1073741824 / 1073741824)
---------------------------
Elapsed time : 0.421 sec
Written : 1.00 GiB
Avg write speed: 2408.12 MiB/s (MB/s)
: 20222.34 Mbit/s (Mbps)
: 2.35 GiB/s
解讀: 此為 NVMe SSD (PCIe 4.0 x4) 在 tmpfs (記憶體檔案系統) 上的測試結果,反映 CPU/記憶體複製速度而非實際磁碟極限。實際磁碟測試請指定掛載於實體磁碟的路徑 (如 `/mnt/nvme/bench.tmp`)。
| 參數 | 建議值 | 影響 |
|---|---|---|
| Buffer Size | 64 KiB ~ 1 MiB | 過小 → 系統呼叫開銷大;過大 → 記憶體壓力、頁面快取效果遞減。64 KiB~256 KiB 為甜蜜點。 |
| Total Bytes | ≥ 1 GiB (HDD) / ≥ 4 GiB (SSD) | 太小受快取影響大,無法反映持續寫入效能。SSD 需更大量觸發 SLC 快取耗盡後的 TLC/QLC 原生速度。 |
| O_DIRECT / sync | fopen($file, 'wb') + stream_set_write_buffer($fp, 0) | 繞過頁面快取,測得「真實落盤速度」。需檔案系統支援 (ext4/XFS/NTFS 支援)。 |
| 多執行緒/非同步 I/O | PHP 不支援原生 async I/O;可用 `pcntl_fork` 多進程並行寫入不同檔案/位移,或改用 `fio`、`dd`、`crystalDiskMark` 專業工具。 |
PHP 腳本適合 **快速驗證、輕量環境 (無 root/管理員權限)、整合至 PHP 應用部署流程**。追求精準、可重現、多維度 (IOPS、延遲分佈、CPU 佔用) 的儲存效能評估,**請使用 fio 或 CrystalDiskMark 等專業基準工具**。