在Ubuntu上進行PHP性能監控,可以采用以下幾種方法和工具:
sudo pecl install xhprof
sudo echo "extension=xhprof.so" > /etc/php/7.4/mods-available/xhprof.ini
sudo phpenmod xhprof
php -m | grep xhprof
<?php
// 開啟性能分析
$xhprof_data = xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
// 你的業務代碼
function heavyCalculation() {
$result = 0;
for ($i = 0; $i < 1000000; $i++) {
$result += $i;
}
return $result;
}
heavyCalculation();
// 獲取性能數據
$xhprof_data = xhprof_disable();
// 保存分析數據
$XHPROF_ROOT = '/path/to/xhprof';
include_once $XHPROF_ROOT . '/xhprof_lib/utils/xhprof_lib.php';
include_once $XHPROF_ROOT . '/xhprof_lib/utils/xhprof_runs.php';
$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($xhprof_data, "test");
?>
<?php
class PerformanceTest {
public function slowOperation() {
sleep(1);
return $this->fastOperation();
}
public function fastOperation() {
return array_sum(range(1, 1000));
}
}
// 開啟性能分析
$xhprof_data = xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
// 執行測試代碼
$test = new PerformanceTest();
$test->slowOperation();
// 獲取并分析數據
$data = xhprof_disable();
print_r($data);
?>
sudo apt update
sudo apt install htop
htop
sudo apt update
sudo apt install sysstat
vmstat
sudo apt update
sudo apt install sysstat
iostat -c -d 4
sudo apt update
sudo apt install sysstat
sar -u 1
sar -d 1
sudo apt update
sudo apt install dstat
dstat -ta 6
sudo apt update
sudo apt install glances
glances
通過上述工具和方法,可以有效地監控PHP應用程序和Linux服務器的性能,及時發現并解決潛在問題,確保系統的穩定運行。