PHP Classes

How Can PHP Monitor Script Execution Time Using the Package Time Warden: Measure PHP execution time and invoke callbacks

Recommend this page to a friend!
  Info   View files Documentation   View files View files (27)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-05-20 (12 days ago) RSS 2.0 feedNot yet rated by the usersTotal: 8 This week: 2All time: 11,324 This week: 29Up
Version License PHP version Categories
time-warden 1.0Custom (specified...8.2Time and Date, Debug, Performance and..., P...
Description 

Author

This package can measure PHP execution time and invoke callbacks.

It can start tracking the time of an initiated task and finish measuring time after a callback function is called.

The package can also invoke a given callback function when the current execution time exceeds a given limit.

Picture of tomloprod
  Performance   Level  
Name: tomloprod <contact>
Classes: 3 packages by
Country: Spain Spain

Documentation

<p align="center">

<p align="center">
    <a href="https://github.com/tomloprod/time-warden/actions"><img alt="GitHub Workflow Status (master)" src="https://github.com/tomloprod/time-warden/actions/workflows/tests.yml/badge.svg"></a>
    <a href="https://packagist.org/packages/tomloprod/time-warden"><img alt="Total Downloads" src="https://img.shields.io/packagist/dt/tomloprod/time-warden"></a>
    <a href="https://packagist.org/packages/tomloprod/time-warden"><img alt="Latest Version" src="https://img.shields.io/packagist/v/tomloprod/time-warden"></a>
    <a href="https://packagist.org/packages/tomloprod/time-warden"><img alt="License" src="https://img.shields.io/packagist/l/tomloprod/time-warden"></a>
</p>

</p>

?? About TimeWarden

TimeWarden is a lightweight PHP library that allows you to monitor the processing time of tasks (useful during the development stage and debugging) and also lets you set estimated execution times for tasks, enabling reactive actions when tasks exceed their estimated duration.

TimeWarden is framework-agnostic, meaning it's not exclusive to any particular framework. It can seamlessly integrate into any PHP application, whether they utilize frameworks like Laravel (?), Symfony, or operate without any framework at all.

? Getting Started

Reactive Actions

You can specify an estimated execution time for each task and set an action to be performed when the time is exceeded (example: send an email, add an entry to the error log, etc.).

Example

timeWarden()->task('Checking articles')->start();

foreach ($articles as $article) {
    // Perform long process... ? 
}

// Using traditional anonymous function
timeWarden()->stop(static function (Task $task): void {
    $task->onExceedsMilliseconds(500, static function (Task $task): void {
        // Do what you need, for example, send an email ?
        Mail::to('foo@bar.com')->queue(
            new SlowArticleProcess($task)
        );
    });
});

// Or using an arrow function
timeWarden()->stop(static function (Task $task): void {
    $task->onExceedsMilliseconds(500, fn (Task $task) => Log::error($task->name.' has taken too long'));
});

Available methods

If you're not convinced about using onExceedsMilliseconds, you have other options:

$task->onExceedsSeconds(10, function () { ... });
$task->onExceedsMinutes(5, function () { ... });
$task->onExceedsHours(2, function () { ... });

Execution Time Debugging

It allows you to measure the execution time of tasks in your application, as well as the possibility of adding those tasks to a group.

Simple tasks

timeWarden()->task('Articles task');

foreach ($articles as $article) {
    // Perform long process...
}

// Previous task is automatically stopped when a new task is created
timeWarden()->task('Customers task');

foreach ($customers as $customer) {
    // Perform long process...
}

echo timeWarden()->output();

Result:

?????????????????????? TIMEWARDEN ??????????????????????
? GROUP               ? TASK           ? DURATION (MS) ?
????????????????????????????????????????????????????????
? default (320.37 ms) ? Articles task  ? 70.23         ?
?                     ? Customers task ? 250.14        ?
??????????????????? Total: 320.37 ms ???????????????????

Grouped tasks

timeWarden()->group('Articles')->task('Loop of articles')->start();

foreach ($articles as $article) {
    // Perform first operations
}

timeWarden()->task('Other articles process')->start();
Foo::bar();

// Previous task is automatically stopped when a new task is created
timeWarden()->group('Customers')->task('Customers task')->start();

foreach ($customers as $customer) {
    // Perform long process...
}

timeWarden()->task('Other customer process')->start();
Bar::foo();

echo timeWarden()->output();

Result:

??????????????????????????? TIMEWARDEN ???????????????????????????
? GROUP                 ? TASK                   ? DURATION (MS) ?
??????????????????????????????????????????????????????????????????
? Articles (85.46 ms)   ? Loop of articles       ? 70.24         ?
?                       ? Other articles process ? 15.22         ?
??????????????????????????????????????????????????????????????????
? Customers (280.46 ms) ? Customers task         ? 250.22        ?
?                       ? Other customer process ? 30.24         ?
???????????????????????? Total: 365.92 ms ????????????????????????

? Tip

If your application has any logging system, it would be a perfect place to send the output.

if (app()->environment('local')) {
    Log::debug(timeWarden()->output());
}

Ways of using TimeWarden

You can use TimeWarden either with the aliases timeWarden() (or timewarden()):

timeWarden()->task('Task 1')->start();

or by directly invoking the static methods of the TimeWarden facade:

TimeWarden::task('Task 1')->start();

You decide how to use it ?

? Architecture

TimeWarden is composed of several types of elements. Below are some features of each of these elements.

TimeWarden

Tomloprod\TimeWarden\Support\Facades\TimeWarden is a facade that acts as a simplified interface for using the rest of the TimeWarden elements.

Methods

Most methods in this class return their own instance, allowing fluent syntax through method chaining.

// Destroys the TimeWarden instance and returns a new one.
TimeWarden::reset(): TimeWarden

// Creates a new group.
TimeWarden::group(string $groupName): TimeWarden

// Creates a new task inside the last created group 
// or within the TimeWarden instance itself.
TimeWarden::task(string $taskName): TimeWarden

// Starts the last created task
TimeWarden::start(): TimeWarden

// Stops the last created task
TimeWarden::stop(): TimeWarden

// Obtains all the created groups
TimeWarden::getGroups(): array

// Returns a table with execution time debugging info 
// (ideal for displaying in the console).
TimeWarden::output(): string

Additionally, it has all the methods of the Taskable interface.

Task

All tasks you create are instances of Tomloprod\TimeWarden\Task. The most useful methods and properties of a task are the following:

Properties

  • `name`

Methods

$task = new Task('Task 1');

$task->start(): void
$task->stop(?callable $fn = null): void

// Returns the duration of the task in a human-readable format. Example: 1day 10h 20min 30sec 150ms
$task->getFriendlyDuration(): string
// Returns the duration of the task in milliseconds
$task->getDuration(): float

// Returns the taskable element to which the task belongs.
$task->getTaskable(): ?Taskable

$task->hasStarted(): bool
$task->hasEnded(): bool

$task->getStartDateTime(): ?DateTimeImmutable
$task->getEndDateTime(): ?DateTimeImmutable

$task->getStartTimestamp(): float
$task->getEndTimestamp(): float

// Reactive execution time methods
$task->onExceedsMilliseconds(float $milliseconds, callable $fn): ?self
$task->onExceedsSeconds(float $seconds, callable $fn): ?self
$task->onExceedsMinutes(float $minutes, callable $fn): ?self
$task->onExceedsHours(float $hours, callable $fn): ?self

Group

All groups you create are instances of the Tomloprod\TimeWarden\Group object. The most useful methods and properties of a group are the following:

Properties

  • `name`

Methods


// Starts the last created task inside this group
$group->start(): void

Additionally, it has all the methods of the Taskable interface.

Taskable

Tomloprod\TimeWarden\Contracts\Taskable is the interface used by the TimeWarden instance as well as by each task group

Methods

// Create a new task within the taskable.
$taskable->createTask(string $taskName): Task;

// Remove the last task from the taskable and add another in its place.
$taskable->replaceLastTask(Task $task): void;

$taskable->getTasks(): array;

$taskable->getLastTask(): ?Task;

// Return the total time in milliseconds of all tasks within the taskable.
$taskable->getDuration(): float;

? Installation & Requirements

> Requires PHP 8.2+

You may use Composer to install TimeWarden into your PHP project:

composer require tomloprod/time-warden

????? Contributing

Contributions are welcome, and are accepted via pull requests. Please review these guidelines before submitting any pull requests.

TimeWarden was created by Tomás López and open-sourced under the MIT license.


  Files folder image Files  
File Role Description
Files folder image.github (1 file, 1 directory)
Files folder imagesrc (2 files, 4 directories)
Files folder imagetests (3 files, 3 directories)
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file CHANGELOG.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file CONTRIBUTING.md Data Auxiliary data
Accessible without login Plain text file LICENSE.md Lic. License text
Accessible without login Plain text file phpstan.neon.dist Data Auxiliary data
Accessible without login Plain text file phpunit.xml.dist Data Auxiliary data
Accessible without login Plain text file pint.json Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation
Plain text file rector.php Class Class source

  Files folder image Files  /  .github  
File Role Description
Files folder imageworkflows (2 files)
  Accessible without login Plain text file FUNDING.yml Data Auxiliary data

  Files folder image Files  /  .github  /  workflows  
File Role Description
  Accessible without login Plain text file formats.yml Data Auxiliary data
  Accessible without login Plain text file tests.yml Data Auxiliary data

  Files folder image Files  /  src  
File Role Description
Files folder imageConcerns (1 file)
Files folder imageContracts (1 file)
Files folder imageServices (1 file)
Files folder imageSupport (1 file, 1 directory)
  Plain text file Group.php Class Class source
  Plain text file Task.php Class Class source

  Files folder image Files  /  src  /  Concerns  
File Role Description
  Plain text file HasTasks.php Class Class source

  Files folder image Files  /  src  /  Contracts  
File Role Description
  Plain text file Taskable.php Class Class source

  Files folder image Files  /  src  /  Services  
File Role Description
  Plain text file TimeWardenManager.php Class Class source

  Files folder image Files  /  src  /  Support  
File Role Description
Files folder imageFacades (1 file)
  Accessible without login Plain text file TimeWardenAlias.php Aux. Auxiliary script

  Files folder image Files  /  src  /  Support  /  Facades  
File Role Description
  Plain text file TimeWarden.php Class Class source

  Files folder image Files  /  tests  
File Role Description
Files folder imageContracts (1 file)
Files folder imageServices (1 file)
Files folder imageSupport (1 file, 1 directory)
  Accessible without login Plain text file ArchTest.php Example Example script
  Accessible without login Plain text file GroupTest.php Example Example script
  Plain text file TaskTest.php Class Class source

  Files folder image Files  /  tests  /  Contracts  
File Role Description
  Plain text file TaskableTest.php Class Class source

  Files folder image Files  /  tests  /  Services  
File Role Description
  Plain text file TimeWardenManagerTest.php Class Class source

  Files folder image Files  /  tests  /  Support  
File Role Description
Files folder imageFacades (1 file)
  Plain text file TimeWardenAliasTest.php Class Class source

  Files folder image Files  /  tests  /  Support  /  Facades  
File Role Description
  Plain text file TimeWardenTest.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:8
This week:2
All time:11,324
This week:29Up