PHPackages                             tomloprod/time-warden - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. tomloprod/time-warden

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

tomloprod/time-warden
=====================

TimeWarden is a lightweight PHP library that enables you to monitor the processing time of tasks and task groups (useful during the development stage). Additionally, it allows you to set maximum execution times to tasks, empowering proactive actions when tasks exceed their planned duration.

v2.0.0(1y ago)16717.9k↓74.1%7[1 issues](https://github.com/tomloprod/time-warden/issues)MITPHPPHP ^8.2.0CI passing

Since May 20Pushed 1y ago3 watchersCompare

[ Source](https://github.com/tomloprod/time-warden)[ Packagist](https://packagist.org/packages/tomloprod/time-warden)[ Fund](https://www.paypal.com/paypalme/tomloprod)[ RSS](/packages/tomloprod-time-warden/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (6)Dependencies (4)Versions (8)Used By (0)

 [![GitHub Workflow Status (master)](https://github.com/tomloprod/time-warden/actions/workflows/tests.yml/badge.svg)](https://github.com/tomloprod/time-warden/actions) [![Total Downloads](https://camo.githubusercontent.com/2bbfea4fe56b3438b81d2a538e65f7eb5367a95d9612eec59eb617f65a9f3572/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f6d6c6f70726f642f74696d652d77617264656e)](https://packagist.org/packages/tomloprod/time-warden) [![Latest Version](https://camo.githubusercontent.com/0b6e57cbc3a8248d34e5917dbb77d46f35ab560e8673d66675c27c9232fc5c83/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f6d6c6f70726f642f74696d652d77617264656e)](https://packagist.org/packages/tomloprod/time-warden) [![License](https://camo.githubusercontent.com/edbdbf474ee66ea0f816d2b300cfe5c1fc436631b7cae1665d610c218ba070d5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f6d6c6f70726f642f74696d652d77617264656e)](https://packagist.org/packages/tomloprod/time-warden)

---

⏱️ **About TimeWarden**
-----------------------

[](#️-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 uses **high-resolution timing** (`hrtime`) for **nanosecond precision**, ensuring accurate measurements even for very fast operations.

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**
---------------------

[](#-getting-started)

### Reactive Actions

[](#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

[](#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

[](#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 () { ... });
```

### Quick Measurement

[](#quick-measurement)

TimeWarden provides a convenient `measure()` method that automatically handles task creation, starting, and stopping for you. This method executes a callable and returns the execution time in milliseconds.

#### Example

[](#example-1)

```
// Simple measurement
$duration = timeWarden()->measure(function() {
    // Your code here
    sleep(1);
    processData();
});

echo "Execution took: {$duration} ms";

// With custom task name
$duration = timeWarden()->measure(function() {
    // Your code here
    processArticles();
}, 'Processing Articles');

// The task will appear in your TimeWarden output with the specified name
echo timeWarden()->output();
```

The `measure()` method:

- Automatically creates a task with the provided name (or 'callable' by default)
- Starts timing before execution
- Executes your callable
- Stops timing after execution (even if an exception occurs)
- Returns the duration in milliseconds
- Integrates with groups and the TimeWarden workflow

### Execution Time Debugging

[](#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

[](#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...
}

/**
 * You can print the results directly or obtain a
 * summary with the `getSummary()` method
 */
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

[](#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();

/**
 * You can print the results directly or obtain a
 * summary with the `getSummary()` method
 */
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

[](#-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

[](#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**
------------------

[](#-architecture)

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

### `TimeWarden`

[](#timewarden)

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

#### Methods

[](#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

// Measures the execution time of a callable and returns duration in milliseconds
TimeWarden::measure(callable $fn, ?string $taskName = null): float

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

/**
 * It allows you to obtain a TimeWardenSummary instance,
 * which is useful for getting a summary of all groups
 * and tasks generated by TimeWarden.
 *
 * Through that instance, you can retrieve the summary
 * in array or string (JSON) format.
 */
TimeWarden::getSummary(): TimeWardenSummary

/**
 * 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](#taskable) interface.

### `Task`

[](#task)

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

#### Properties

[](#properties)

- `name`

#### Methods

[](#methods-1)

```
$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

// Returns the start and end timestamps in nanoseconds (high precision)
$task->getStartTimestamp(): int
$task->getEndTimestamp(): int

/** @return array */
$task->toArray(): array

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

### `Group`

[](#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

[](#properties-1)

- `name`

#### Methods

[](#methods-2)

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

Additionally, it has all the methods of the [Taskable](#taskable) interface.

### `Taskable`

[](#taskable)

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

#### Methods

[](#methods-3)

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

$taskable->getTasks(): array

$taskable->getLastTask(): ?Task

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

$taskable->toArray(): array

$taskable->toJson(): string
```

### `TimeWardenSummary`

[](#timewardensummary)

`Tomloprod\TimeWarden\TimeWardenSummary` is a class that allows obtaining a general summary of groups and their tasks generated with TimeWarden.

It is useful for obtaining a summary in array or string (JSON) format.

You can obtain an instance of `TimeWardenSummary` as follows:

```
/** @var Tomloprod\TimeWarden\TimeWardenSummary $timeWardenSummary */
$timeWardenSummary = timeWarden()->getSummary();
```

#### Methods

[](#methods-4)

```
$timeWardenSummary->toArray(): array
$timeWardenSummary->toJson(): string
```

Here is an example of the data returned in array format:

```
$summaryArray = [
    [
        'name' => 'default',
        'duration' => 42.0,
        'tasks' => [
            [
                'name' => 'TaskName1',
                'duration' => 19.0,
                'friendly_duration' => '19ms',
                'start_timestamp' => 1496664000000000000, // nanoseconds
                'end_timestamp' => 1496664000019000000,   // nanoseconds
                'start_datetime' => '2017-06-05T12:00:00+00:00',
                'end_datetime' => '2017-06-05T12:00:00+00:00',
            ],
            [
                'name' => 'TaskName2',
                'duration' => 23.0,
                'friendly_duration' => '23ms',
                'start_timestamp' => 1496664000000000000, // nanoseconds
                'end_timestamp' => 1496664000023000000,   // nanoseconds
                'start_datetime' => '2017-06-05T12:00:00+00:00',
                'end_datetime' => '2017-06-05T12:00:00+00:00',
            ],
        ],
    ],
    [ // Others groups... ],
];
```

**🚀 Installation &amp; Requirements**
-------------------------------------

[](#-installation--requirements)

> **Requires [PHP 8.2+](https://php.net/releases/)**

You may use [Composer](https://getcomposer.org) to install TimeWarden into your PHP project:

```
composer require tomloprod/time-warden
```

**🧑‍🤝‍🧑 Contributing**
----------------------

[](#‍‍-contributing)

Contributions are welcome, and are accepted via pull requests. Please [review these guidelines](./CONTRIBUTING.md) before submitting any pull requests.

---

**TimeWarden** was created by **[Tomás López](https://twitter.com/tomloprod)** and open-sourced under the **[MIT license](https://opensource.org/licenses/MIT)**.

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance49

Moderate activity, may be stable

Popularity43

Moderate usage in the ecosystem

Community11

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~66 days

Recently: every ~91 days

Total

7

Last Release

377d ago

Major Versions

v1.2.3 → v2.0.02025-06-22

### Community

Maintainers

![](https://www.gravatar.com/avatar/1c9df012919bdcf3f17fad0e3a84ec77641f1f9671f85cb9c4377242ba09dde8?d=identicon)[tomloprod](/maintainers/tomloprod)

---

Top Contributors

[![tomloprod](https://avatars.githubusercontent.com/u/7898894?v=4)](https://github.com/tomloprod "tomloprod (30 commits)")

---

Tags

debuggingfluent-apimonitoring-toolperformancephpmonitoringperformancedebuggingexecution timetomloprodtime-warden

###  Code Quality

TestsPest

Static AnalysisRector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/tomloprod-time-warden/health.svg)

```
[![Health](https://phpackages.com/badges/tomloprod-time-warden/health.svg)](https://phpackages.com/packages/tomloprod-time-warden)
```

###  Alternatives

[rollbar/rollbar

Monitors errors and exceptions and reports them to Rollbar

34424.8M87](/packages/rollbar-rollbar)[ekino/newrelic-bundle

Integrate New Relic into Symfony2

28511.3M8](/packages/ekino-newrelic-bundle)[analog/analog

Fast, flexible, easy PSR-3-compatible PHP logging package with dozens of handlers.

3511.6M24](/packages/analog-analog)[jackwh/laravel-new-relic

Monitor your Laravel application performance with New Relic

113980.0k](/packages/jackwh-laravel-new-relic)[honeybadger-io/honeybadger-laravel

Honeybadger Laravel integration

431.3M](/packages/honeybadger-io-honeybadger-laravel)[honeybadger-io/honeybadger-php

Honeybadger PHP library

381.6M5](/packages/honeybadger-io-honeybadger-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
