PHP 程序运行时长可通过以下方式判断:直接方式:使用 microtime(true) 函数获取运行前后的时间戳,相减得到运行时长。间接方式:将执行时间作为命令行参数传递,使用 time_elapsed() 函数获取运行时长。使用 Xdebug 扩展:启用 profiler_enable 选项,可在输出中找到运行时长。使用 cProfile 模块:使用 run() 方法运行代码,调用 print_stats() 方法显示运行时长。

如何判断 PHP 程序运行时长
直接方式:
使用 microtime(true) 函数获得当前时间戳(以秒为单位),并将运行前和运行后的时间戳之差作为程序运行时长。
示例:
立即学习“PHP免费学习笔记(深入)”;
<code class="php">$startTime = microtime(true); // 运行程序代码 $endTime = microtime(true); echo "程序运行时长:" . ($endTime - $startTime) . " 秒";</code>
间接方式:
将脚本执行时间作为命令行参数传递给脚本,并在脚本中使用 time_elapsed() 函数获得运行时长。
调用示例:
<code class="bash">php /path/to/script.php --time-elapsed</code>
脚本中获取运行时长:
<code class="php">if (isset($_SERVER['argv'][1]) && $_SERVER['argv'][1] == '--time-elapsed') {
echo "程序运行时长:" . time_elapsed() . " 秒";
}
function time_elapsed() {
return time() - $_SERVER['REQUEST_TIME_FLOAT'];
}</code>使用 Xdebug 扩展:
启用 Xdebug 扩展并将其 profiler_enable 选项设置为 true,程序运行完成后可在 Xdebug 的输出中找到程序运行时长。
使用 cProfile 模块:
导入 cProfile 模块,使用 run() 方法运行程序代码,并在运行完成后调用 print_stats() 方法显示运行时长和其他性能信息。
示例:
立即学习“PHP免费学习笔记(深入)”;
<code class="php">require 'cProfile.php'; cProfile::run(); cProfile::print_stats();</code>











