PHPackages                             green-elephpant/code-bench - 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. green-elephpant/code-bench

ActiveLibrary

green-elephpant/code-bench
==========================

Code benchmark tool

v1.1.0(9mo ago)020[1 PRs](https://github.com/green-elephpant/code-bench/pulls)1MITPHPPHP &gt;=7.4CI passing

Since Sep 25Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/green-elephpant/code-bench)[ Packagist](https://packagist.org/packages/green-elephpant/code-bench)[ RSS](/packages/green-elephpant-code-bench/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (3)Versions (6)Used By (1)

 [![Green ElePHPant](./docs/images/green-elephpant-logo.svg)](./docs/images/green-elephpant-logo.svg)

Green ElePHPant - CodeBench
===========================

[](#green-elephpant---codebench)

The **Green ElePHPant** wants to help you to reduce the carbon emissions of your software.

One way of doing so is to optimize the performance. Less CPU, RAM and Storage means reduced energy consumption, fewer carbon emissions, and less hardware to be produced. And, last but not least, the users of your software will benefit from a faster application.

`GreenElephpant\CodeBench` is a simple benchmark tool that can help you to improve the performance of your code by benchmarking several possible solutions and helps you to decide which code to chose.

Key concept
-----------

[](#key-concept)

`GreenElephpant\CodeBench` simply measures the execution time and memory consumption of callables, which contain the code you want to measure.

Shout-out to [PhpBench](https://github.com/phpbench/phpbench), which is a much better solution if you need super accurate measurement, because it runs the code to be measured in isolation. It also is meant to be used as test suite similar to PHPUnit and can thus be used to catch performance regressions during CI/CD, which makes it extremely useful . However, `GreenElephpant\CodeBench` is your coding compadre if a quick and rough measurement is enough to decide between several options.

Installation
------------

[](#installation)

Simply use composer to add `GreenElephpant\CodeBench` to your project:

`composer require green-elephpant/code-bench --dev`

*Note:* we use `require-dev` here, since `GreenElephpant\CodeBench` should not be used in production code.

*Note:* for Laravel, you can use the package [CodeBench Laravel](https://github.com/green-elephpant/code-bench-laravel).

*Note:* `GreenElephpant\CodeBench` works with PHP 7.4+ to support most code bases. However, only since PHP 8.2 the function[memory\_reset\_peak\_usage](https://www.php.net/manual/en/function.memory-reset-peak-usage.php) is available. With earlier versions, you will not be able to monitor the peak memory usage with this tool.

Configuration
-------------

[](#configuration)

`GreenElephpant\CodeBench` is designed to require no other dependencies to keep its footprint small, so there is nothing much to do.

### Set Logger callable

[](#set-logger-callable)

By default, `GreenElephpant\CodeBench` uses `print` for logging. However, you can set a callable which takes the output and you can log it where you want.

For example, in Laravel you could do

```
CodeBench::$loggerCallable = function (string $text) {
    Log::debug($text);
};
```

to use whatever logger you have defined.

*Note*: the [CodeBench Laravel](https://github.com/green-elephpant/code-bench-laravel) package does that for you.

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

In its purest form, the usage is as easy as the following function call:

```
use GreenElephpant\CodeBench\CodeBench;

CodeBench::benchmark([
    function () {
        // The first option we want to test
        date('D M d Y H:m:s');
    },
    function () {
        // The second option we want to test
        (new DateTime())->format('D M d Y H:m:s');
    }
]);
```

The result should be something similar to this:

```
Function 1
Time (seconds): 0.00000310 (Reference)
Memory (MB): 0.00000000 (Reference)
Memory Peak (MB): 0.00000000 (Reference)

Function 2
Time (seconds): 0.00000405 (=> 1.31x)
Memory (MB): 0.00000000 (=> 0.00x)
Memory Peak (MB): 0.00000000 (=> 0.00x)

```

What does the output mean?

- `Time (seconds)` tells us the time in seconds that the callable needed to execute. Since the example is just a simple function call, it's just a fraction of a second.
- `Memory (MB)` is the difference of the used memory before and after the callable was executed
- `Memory Peak (MB)` is the biggest amount of memory (aka the peak) the callable required during its execution. Since PHP frees memory during the execution time, this measurement is much more important if you want to find out if the callable can hit the configured PHP memory limit.

### Iterations

[](#iterations)

Results can vary between several executions of the callable. To balance out any outliers, we can run several iterations and take the average. This behaviour is controlled by the `$iterations` parameter. The following example will run the each callable 100 times:

```
GreenElephpant\CodeBench\CodeBench::benchmark([
    function () {
        date('D M d Y H:m:s');
    },
    function () {
        (new DateTime())->format('D M d Y H:m:s');
    }
], 100);
```

### Pre-run callable

[](#pre-run-callable)

By default, `GreenElephpant\CodeBench` executes the callable one time before starting with the actual measurement. This is to avoid side effects by e.g. cache warmups. To disable this behaviour, run the benchmark with `$preRunCallable` set to `false`:

```
GreenElephpant\CodeBench\CodeBench::benchmark([
    function () {
        date('D M d Y H:m:s');
    },
    function () {
        (new DateTime())->format('D M d Y H:m:s');
    }
], 100, false);
```

### Stopwatch

[](#stopwatch)

You can use the `start()` and `stop()` functions to measure the performance of a code block.

```
use GreenElephpant\CodeBench\CodeBench;

CodeBench::start();

// Your code block here
for ($i = 0; $i < 1000; $i++) {
    expensive_function_call();
}

CodeBench::stop();
```

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance74

Regular maintenance activity

Popularity6

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.2% 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 ~345 days

Total

3

Last Release

276d ago

Major Versions

v0.1.0 → v1.0.02024-09-08

PHP version history (2 changes)v0.1.0PHP &gt;=7.2

v1.0.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/4761678d271eef1bc9fc3478994848dd54b6d77551e3c065b1b730b5badffb90?d=identicon)[carstenwindler](/maintainers/carstenwindler)

---

Top Contributors

[![carstenwindler](https://avatars.githubusercontent.com/u/5927645?v=4)](https://github.com/carstenwindler "carstenwindler (23 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/green-elephpant-code-bench/health.svg)

```
[![Health](https://phpackages.com/badges/green-elephpant-code-bench/health.svg)](https://phpackages.com/packages/green-elephpant-code-bench)
```

PHPackages © 2026

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