zachete/profiler

轻量级类,便于代码性能分析

v1.1 2020-02-26 07:06 UTC

This package is auto-updated.

Last update: 2024-09-26 17:06:27 UTC


README

这是一个轻量级的PHP类,简化了代码性能分析的过程。

安装

composer require zachete/profiler

用法

<?php

use Zachete\Profiler;

$profiler = new Profiler();

$profiler->label('Sleep for 1 second');
sleep(1);

$profiler->label('Sleep for 2 seconds');
sleep(3);

$profiler->get('Sleep for 1 seconds'); // return ~ 4.004
$profiler->get('Sleep for 2 seconds'); // return ~ 3.002

此外,你可以向构造函数提供一个闭包,该闭包将在调用get方法时随时被调用。这可能对记录日志很有用。以下是一个Laravel日志的示例

在AppServiceProvider.php中绑定profiler实例

public function register() {
    $this->app->instance('Zachete\Profiler', new Profiler([
        'logging_function' => function($labelName, $value) {
            info("Profile {$labelName} with {$value} seconds");
        }
    ]));
}

在控制器中使用profiler

// some method
public function someMethod(Profiler $profiler) {
    $profiler->label('some label');

    sleep(4);

    // The code below will also log result
    // using info() method with a provided string
    // ("Profile some label with 4.004 seconds")

    $profiler->get('some label');
}