萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 電腦基礎知識 >  >> 電腦基本常識

PHP 測試硬碟寫入速率腳本:原理、程式碼與結果解讀

應用場景

  • 伺服器上線前驗證儲存子系統效能 (本地 SSD/NVMe、網路儲存 NFS/iSCSI、雲端區塊儲存)。
  • 比較不同檔案系統 (ext4、XFS、ZFS、NTFS、ReFS)、掛載參數、RAID 等級對寫入效能影響。
  • CI/CD 流程中自動化效能基準測試。

核心原理

  • 使用 fwrite() 連續寫入固定大小緩衝區 (預設 512 Bytes) 至檔案,累積至目標總量 (預設 1 GB)。
  • 以 time() 記錄開始/結束 Unix 時間戳 (秒級精度),計算耗時與平均寫入速率。
  • 注意: PHP 預設 `max_execution_time` 可能中斷長時間腳本,需 `set_time_limit(0)` 移除限制;`memory_limit` 不影響檔案串流寫入。

完整腳本 (含進階參數化與單位換算)

<?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 Size64 KiB ~ 1 MiB過小 → 系統呼叫開銷大;過大 → 記憶體壓力、頁面快取效果遞減。64 KiB~256 KiB 為甜蜜點。
Total Bytes≥ 1 GiB (HDD) / ≥ 4 GiB (SSD)太小受快取影響大,無法反映持續寫入效能。SSD 需更大量觸發 SLC 快取耗盡後的 TLC/QLC 原生速度。
O_DIRECT / syncfopen($file, 'wb') + stream_set_write_buffer($fp, 0)繞過頁面快取,測得「真實落盤速度」。需檔案系統支援 (ext4/XFS/NTFS 支援)。
多執行緒/非同步 I/OPHP 不支援原生 async I/O;可用 `pcntl_fork` 多進程並行寫入不同檔案/位移,或改用 `fio`、`dd`、`crystalDiskMark` 專業工具。

專業級替代工具建議

  • fio (Flexible I/O Tester): 行業標準,支援隨機/循序、多佇列、多執行緒、IOPS/延遲/頻寬完整報表、JSON 輸出。
  • CrystalDiskMark (Windows GUI): 直觀、支援 NVMe/RAID/網路磁碟、預設 1GiB/4KiB Q32T1/Q8T1/1T1 等標準配置。
  • dd (Linux/Unix): `dd if=/dev/zero of=/mnt/test/bench bs=1M count=4096 oflag=direct,sync` 快速單指令測試。
  • ATTO Disk Benchmark / AS SSD Benchmark: Windows 圖形化、壓縮/不可壓縮資料模式對比。

結語

PHP 腳本適合 **快速驗證、輕量環境 (無 root/管理員權限)、整合至 PHP 應用部署流程**。追求精準、可重現、多維度 (IOPS、延遲分佈、CPU 佔用) 的儲存效能評估,**請使用 fio 或 CrystalDiskMark 等專業基準工具**。

copyright © 萬盛學電腦網 all rights reserved