8ctopus/nano-timer

Yet another php timer: measure time between events, log only requests slower than a given threshold, automatically log when the destructor is called and measure peak memory use

2.1.1 2024-01-26 07:36 UTC

This package is auto-updated.

Last update: 2024-04-26 08:13:09 UTC


README

packagist downloads min php version license tests code coverage badge lines of code

Yet another php timer

why another timer?

The main reason for this timer is to analyze slow requests that occur from time to time in production where using tools such as XDebug or php SPX is not advisable.

features

  • measure time between events
  • log only requests slower than a given threshold
  • automatically log when the destructor is called
  • measure peak memory use

install

  • composer require 8ctopus/nano-timer

simple example

use Oct8pus\NanoTimer\NanoTimer;

require_once __DIR__ . '/vendor/autoload.php';

$timer = new NanoTimer();

usleep(200000);

$timer->measure('usleep 200ms');

foreach (range(0, 50000) as $i) {
    $a = $i * $i;
}

$timer->measure('range 0-50000');

echo $timer->table();
usleep 200ms  211ms
range 0-50000  12ms
total         223ms

more advanced

  • log autoload and constructor time
  • log peak memory use
use Oct8pus\NanoTimer\NanoTimer;

// autoload and constructor time
$hrtime = hrtime(true);

require_once __DIR__ . '/vendor/autoload.php';

$timer = new NanoTimer($hrtime);

$timer
    ->logMemoryPeakUse(true);

$timer->measure('autoload and constructor');

usleep(200000);

$timer->measure('200ms sleep');

sleep(1);

$timer->measure('1s sleep');

foreach (range(0, 50000) as $i) {
    $a = $i * $i;
}

$timer->measure('pow range 0-50000');

echo $timer->table();
autoload and constructor   23ms
200ms sleep               211ms
1s sleep                 1012ms
pow range 0-50000          13ms
total                    1259ms
memory peak use             4MB

only log measurements slower than

It's sometimes useful to only log measurements slower than a given threshold.

$timer = new NanoTimer();

$timer
    ->logSlowerThan(100)
    ->autoLog();

...

In this example, the request will automatically be logged to the error log when the destructor is called if the total time spent is more than 100 milliseconds.

nanotimer - total: 614ms - destruct: 614ms

run tests

composer test

clean code

composer fix(-risky)