在 PHP 中跟踪脚本执行时间 [英] Tracking the script execution time in PHP

查看:30
本文介绍了在 PHP 中跟踪脚本执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 必须跟踪特定脚本使用的 CPU 时间量,以强制执行 max_execution_time 限制.

PHP must track the amount of CPU time a particular script has used in order to enforce the max_execution_time limit.

有没有办法在脚本内部访问它?我想在我的测试中包含一些关于实际 PHP 中 CPU 消耗量的日志记录(当脚本等待数据库时,时间不会增加).

Is there a way to get access to this inside of the script? I'd like to include some logging with my tests about how much CPU was burnt in the actual PHP (the time is not incremented when the script is sitting and waiting for the database).

我使用的是 Linux 机器.

I am using a Linux box.

推荐答案

在 unixoid 系统上(以及在 Windows 上的 php 7+ 中),您可以使用 getrusage,比如:

On unixoid systems (and in php 7+ on Windows as well), you can use getrusage, like:

// Script start
$rustart = getrusage();

// Code ...

// Script end
function rutime($ru, $rus, $index) {
    return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
     -  ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}

$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
    " ms for its computations
";
echo "It spent " . rutime($ru, $rustart, "stime") .
    " ms in system calls
";

请注意,如果您为每个测试生成一个 php 实例,则不需要计算差异.

Note that you don't need to calculate a difference if you are spawning a php instance for every test.

这篇关于在 PHP 中跟踪脚本执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆