petrknap/php-profiler

PHP 性能分析器

v1.3.0 2017-05-29 10:14 UTC

This package is auto-updated.

Last update: 2024-09-10 17:02:51 UTC


README

什么是性能分析?

在软件工程中,性能分析(也称为“程序性能分析”、“软件性能分析”)是一种动态程序分析形式,它测量程序的空间(内存)或时间复杂度、特定指令的使用情况,或函数调用频率和持续时间。通常,性能分析信息用于帮助程序优化。-- 性能分析(计算机编程) - 维基百科,自由的百科全书

组件

性能分析

Profile 是性能分析器返回的基本数据结构,也是对所选性能分析器的封装。

用法

如果您想对一段代码进行性能分析,只需将其封装在 Profile::startProfile::finish 调用之间。

<?php

use PetrKnap\Php\Profiler\Profile;
use PetrKnap\Php\Profiler\SimpleProfiler;

SimpleProfiler::enable();
Profile::setProfiler(SimpleProfiler::class);

Profile::start();
/* your code goes here */
var_dump(Profile::finish());

如果您愿意,可以为您的性能分析添加标签。语法与 sprintf 相同。

<?php

use PetrKnap\Php\Profiler\Profile;

Profile::start(/* sprintf( */ "static label" /* ) */);
Profile::start(/* sprintf( */ "line %s", __LINE__ /* ) */);

如果您想创建更详细的分析,可以在另一个分析内部启动新的分析。

<?php

use PetrKnap\Php\Profiler\Profile;

Profile::start("Profile 1");
    /* your code goes here */
    Profile::start("Profile 1.1");
        Profile::start("Profile 1.1.1");
            /* your code goes here */
        Profile::finish("Profile 1.1.1");
        /* your code goes here */
        Profile::start("Profile 1.1.2");
            /* your code goes here */
        Profile::finish("Profile 1.1.2");
        /* your code goes here */
    Profile::finish("Profile 1.1");
Profile::finish("Profile 1");

或者(如果您愿意)可以直接在请求的性能分析器上调用 startfinish 方法。

SimpleProfiler

SimpleProfiler 是一个易于使用且快速的静态类,用于 PHP 代码性能分析。您可以通过它扩展并创建适合您特定用例的特定性能分析器。

<?php

use PetrKnap\Php\Profiler\SimpleProfiler;

SimpleProfiler::enable();

SimpleProfiler::start();
/* your code goes here */
var_dump(SimpleProfiler::finish());

AdvancedProfiler

AdvancedProfilerSimpleProfiler 的高级版本,它支持后处理程序。

<?php

use PetrKnap\Php\Profiler\AdvancedProfiler;
use PetrKnap\Php\Profiler\Profile;

AdvancedProfiler::setPostProcessor(function(Profile $profile) {
    var_dump($profile);
});
AdvancedProfiler::enable();

AdvancedProfiler::start();
/* your code goes here */
AdvancedProfiler::finish();

如何安装

运行 composer require petrknap/php-profiler 或手动将此 JSON 代码与您的项目 composer.json 文件合并,并运行 composer install。您可以使用 已发布的版本之一 而不是 dev-master

{
    "require": {
        "petrknap/php-profiler": "dev-master"
    }
}

或者手动通过 git clone https://github.com/petrknap/php-profiler.git 克隆此仓库或下载 此仓库作为 ZIP 文件,并将其文件提取到您的项目中。