justlunix/timer

There is no license information available for the latest version (v1.0.0) of this package.

A tool to track execution times of tasks

v1.0.0 2023-10-14 10:02 UTC

This package is auto-updated.

Last update: 2024-04-15 10:33:03 UTC


README

A simple tool to track execution times of tasks.

Install

Simply install the package via composer and you're good to go!

composer require justlunix/timer

Usage

Simple tracking of a task

$task = Timer::task('Fetching Customer Data From API', function() {
    // fetching...
});

echo $task->getTaskData()->getReadableTimeRun(); // => 2sec 15ms

Nested task tracking

$task = Timer::task('Handling Web Request', function(TaskData $taskData) {
    $apiTask = Timer::task('Fetching Customer Data From API', function() {
        // fetching...
    }, parent: $taskData);
    $resTask = Timer::task('Building Response', function() use ($apiTask) {
        // building...
    }, parent: $taskData);
    
    return $resTask->result;
});

Subscribe to events

Timer::subscribe(
    PostTaskExecutedEvent::class,
    function (TaskData $taskData) {
        // do something
    }
);

Compare tasks

$issetTestTask = Timer::task('isset() performance', function () {
    // Implement performance test
});
$arraySearchTestTask = Timer::task('array_search() performance', function () {
    // Implement performance test
});

$taskComparison = Timer::compare($issetTestTask->getTaskData(), $arraySearchTestTask->getTaskData());

Cache task results

// Invalidate caches via
Timer::$invalidateCaches = true;

$task = Timer::task('Fetching Customer Data From API', function() {
    // fetching...
}, cacheUntil: new \DateTime('tomorrow'));

$task = Timer::task('Fetching Customer Data From API', function() {
    // fetching...
}); // => Cache hit!

Export statistics

// Export all tasks at the end with
Timer::exportAsFile(__DIR__ . '/timer.txt');

// TODO: or enable live logging into a file
Timer::enableLiveLogging(__DIR__ . '/timer.txt');

// TODO: or log to Spatie Ray!
Timer::enableRay();