php 8.6命令行任务可用hrtime记录单调时间差,用getrusage计算进程用户态和内核态cpu增量,再单独记录php分配器的峰值。墙钟耗时包含等待,cpu时间和内存峰值具有不同口径,不能混成一个性能数字。

PHP手册中的hrtime
给已有任务加一层测量包装
<?php
function cpuSeconds(array $r,string $kind): float {
return (float)($r['ru_'.$kind.'.tv_sec']??0)
+(float)($r['ru_'.$kind.'.tv_usec']??0)/1000000;
}
function measured(callable $job): mixed {
if (PHP_SAPI!=='cli' || PHP_INT_SIZE<8) {
throw new RuntimeException('示例要求64位CLI');
}
$before=getrusage();
if ($before===false) throw new RuntimeException('无法读取进程指标');
memory_reset_peak_usage(); $start=hrtime(true);
try { return $job(); }
finally {
$after=getrusage();
$metrics=['elapsed_ms'=>(hrtime(true)-$start)/1e6,
'php_peak_bytes'=>memory_get_peak_usage(true)];
if ($after!==false) {
$metrics['user_cpu_seconds']=cpuSeconds($after,'utime')-cpuSeconds($before,'utime');
$metrics['system_cpu_seconds']=cpuSeconds($after,'stime')-cpuSeconds($before,'stime');
}
fwrite(STDERR,json_encode($metrics,JSON_THROW_ON_ERROR).PHP_EOL);
}
}
$sum=measured(function(): int {
$total=0;
for ($i=1;$i<=100000;$i++) $total+=$i;
return $total;
});
echo $sum,PHP_EOL;
PHP手册中的getrusage
保持业务输出和指标分开
示例把指标写入标准错误,业务结果仍走标准输出;将包装器中的演示循环换成实际任务时,不要把原始业务数据放进指标日志。finally确保任务抛异常时也会记录已经消耗的资源。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
不要把一次结果当作优化结论
getrusage默认统计当前进程,不包含所有外部服务,也不自动汇总仍在运行的子进程。memory_get_peak_usage(true)报告PHP分配器口径,不等于整个进程RSS。不同系统的ru_maxrss单位可能不同,本例没有把它直接标为字节;比较优化前后应固定输入与环境并重复测量。


















