Skip to content

About

Advanced PHP Benchmark v1.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

13 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PHP Benchmark Script

A simple, lightweight PHP script to measure the performance of your server or hosting environment. It executes various computational tasks and reports the time taken for each.

πŸš€ Overview

This benchmark performs intensive operations to test:

  • Mathematical Performance: Square roots, trigonometry, and complex arithmetic.
  • String Manipulation: Case conversion, reversing, padding (str_pad), hashing, and regex work.
  • Loops & Logic: Performance of basic control structures and iterations.
  • I/O, RNG and OPcache: File read/write throughput, the PHP random-number APIs, and the cost of repeated include calls of the same script.
  • Environment Info: Identifies the PHP version and Server OS.

βš™οΈ Requirements

  • PHP 7.4 or newer (PHP 8.x recommended), a single file and no extensions. bench.php has zero runtime dependencies and never loads Composer: copy the one file to a server and it runs. Composer only appears in the development setup for the PHPUnit suite (see Testing).
  • Write access to the system temporary directory (sys_get_temp_dir()) for the IO and OPcache tests.
  • A default run (scale=1) takes roughly 5 seconds on a typical VPS β€” 4.8 s measured on the author's machine with Xdebug disabled. The 15 s value is the built-in budget ceiling used for the within budget badge, not a target size. Slower or shared hosts should use ?scale=0.5.
  • Disable Xdebug for realistic numbers (XDEBUG_MODE=off or remove the extension); it inflates every timing by a large factor and makes the results incomparable with the sample below.

v2.0.0 changed the iteration counts of every benchmark and the way results are measured (warmup pass, hrtime(), peak-memory delta, ops/s). Results from 2.x are not comparable with 1.x numbers.

πŸ“₯ How to Download

Option 1: Via Terminal (SSH)

Use wget or curl to download the file directly to your public directory:

wget https://raw.githubusercontent.com/gr8man/PHP_Benchmark/refs/heads/main/bench.php

or

curl -O https://raw.githubusercontent.com/gr8man/PHP_Benchmark/refs/heads/main/bench.php

Option 2: Manual Download

  1. Download the bench.php file from this repository.
  2. Upload it to your server using FTP (e.g., FileZilla) or your hosting control panel's file manager.

πŸ› οΈ Usage

Once the file is on your server, simply access it through your web browser:

http://your-domain.com/bench.php

The script will execute immediately and display a table with the results.

Note: Lower execution times indicate a faster server.

Query parameters

Parameter Example Description
scale ?scale=0.5 Multiplies every iteration count. A missing, non-numeric, 0 or negative value falls back to 1.0; any value greater than 0 is clamped into 0.1 – 4.0 (default 1.0). Use it to fit slower hosts or stricter time limits.
format ?format=json Returns JSON (Content-Type: application/json) instead of the HTML report.
private ?private=1 Hides the OS and server software strings (hidden).
token ?token=... Access token; only required when the BENCH_TOKEN environment variable is set.

CLI usage

php bench.php
php bench.php --scale=0.5
php bench.php --format=json
php bench.php --private

--format=json prints the same document as ?format=json, so it can be piped into jq or parsed by other tools.

Access token and privacy

  • Set BENCH_TOKEN=some-secret in the web server environment to require ?token=some-secret (compared with hash_equals()). The check runs before any output and before the lock is taken; requests without a matching token get 403 Forbidden. With BENCH_TOKEN unset nothing changes: the report runs immediately.
  • Set BENCH_PRIVATE=1 (or append ?private=1) to redact both the php_uname() output (php.os in JSON) and the SERVER_SOFTWARE value (Server row in HTML).
  • Responses are sent with noindex, nofollow, nosniff and no-store headers; a lock file prevents two reports from running concurrently. A busy lock returns HTTP 409 with exit code 1, and the body follows the requested format: JSON requests get {"version":"2.0.0","error":"already_running","message":"Benchmark already running in another process"}, everything else gets a small HTML notice.
  • If the lock file itself cannot be opened, the report still runs: HTML shows a warning row and JSON reports "concurrency_guard": false under env.

Columns

Column Meaning
Test Benchmark name with its group tag.
Iter Effective iteration count (base count Γ— scale).
Time Duration of the measured pass only (the warmup pass is excluded), with a relative bar (100% = slowest successful test).
ops/s Iterations per second (count / seconds). Rows that ended with an error show – because they have no defined throughput.
Peak Mem Delta of memory_get_peak_usage() around the measured pass. It is a cumulative process peak, so most rows report 0 B; large allocations show up once.

A warmup pass (5% of the iterations, capped at 5000) runs before every measurement and is not counted in the Time column, and the RNG is seeded per test so str_shuffle/shuffle/rand workloads stay reproducible.

Accounting notes

  • Total Time (header) covers the whole run: every warmup pass, the harness overhead and the measured passes. It is therefore larger than the sum of the Time column; the header element carries the same explanation as a tooltip / aria-label.
  • IO::File Write measures buffered fwrite() throughput with one fopen/fclose pair per test, not one open per iteration.
  • Rand::rand and Rand::mt_rand share the same Mersenne Twister engine since PHP 7.1 (rand() is an alias of mt_rand()), so both rows measure the same generator. They are kept for historical continuity; do not read their difference as an engine difference.
  • OPcache: Repeated File Include re-includes a generated ~240 KB PHP file. With opcache.enable_cli=0 (the default on most installs) a CLI run measures re-parsing and re-compiling the file on every include, not OPcache cache hits; export opcache.enable_cli=1 (or enable OPcache for the SAPI you use) to observe cached includes. The temporary file is created once per process by tempnam() during the unmeasured warmup, and the file generation (var_export() + file_put_contents()) is excluded from the measured pass.

πŸ“„ JSON output

?format=json (and --format=json) emits the document built by PhpBenchmark::toArray():

{
    "version": "2.0.0",
    "generated_at": "2026-11-18T20:00:00+00:00",
    "scale": 1,
    "php": {
        "version": "8.3.14",
        "sapi": "cli",
        "os": "Linux 6.2.0 (x86_64)"
    },
    "env": {
        "memory_limit": "128M",
        "max_execution_time": 0,
        "opcache": true,
        "jit": false,
        "concurrency_guard": true
    },
    "tests": [
        {
            "name": "Math (Trigonometry & Powers)",
            "group": "compute",
            "count": 80000,
            "seconds": 0.3149,
            "ops_per_sec": 254049.0,
            "peak_mem_bytes": 0,
            "error": null
        }
    ],
    "total": {
        "seconds": 4.8411,
        "peak_mem_bytes": 2097152,
        "within_budget": true,
        "budget_seconds": 15
    }
}
Key Type Notes
version string Harness version (2.0.0).
generated_at string ISO 8601 timestamp in UTC.
scale number Effective scale after clamping (0.1 – 4.0, default 1.0).
php.version string PHP_VERSION.
php.sapi string PHP_SAPI.
php.os string php_uname() summary, or "hidden" in private mode.
env.memory_limit string ini_get('memory_limit') as text ("-1" = unlimited).
env.max_execution_time int ini_get('max_execution_time') in seconds (0 = no limit).
env.opcache bool OPcache enabled for this SAPI.
env.jit bool JIT enabled.
env.concurrency_guard bool false only when the lock file could not be opened and the run continued without the single-run guard.
tests[].name string Benchmark name.
tests[].group string Group tag shown under the name in the HTML table (compute, strings, random, io, jit, general, …).
tests[].count int Effective iteration count (base count Γ— scale, minimum 1).
tests[].seconds number Raw duration of the measured pass in seconds, unrounded.
tests[].ops_per_sec number count / seconds for successful rows, exactly 0 for rows with a non-null error.
tests[].peak_mem_bytes int memory_get_peak_usage() delta around the measured pass.
tests[].error string | null Exception message when the measured pass threw, otherwise null.
total.seconds number Wall-clock duration of the whole run (warmup included).
total.peak_mem_bytes int Process-wide peak memory at the end of the run.
total.within_budget bool total.seconds <= budget_seconds.
total.budget_seconds number Budget ceiling, emitted as a number: an integer when the value is whole (15).

Failed rows keep their nominal count but are excluded from throughput: ops_per_sec is 0 and the HTML relative-time bar for that row is rendered with zero width. Per-test seconds and ops_per_sec are not rounded, so ops_per_sec === count / seconds holds for every row with error: null. If json_encode() ever fails, the document keeps the same top-level keys with tests: [] and "error": "json_encode_failed" instead of degrading to a stub.

πŸ§ͺ Testing

bench.php is verified by a PHPUnit 9.6 suite that treats the script as a black box: it runs the file as a CLI process, includes it in library mode and drives it through PHP's built-in web server.

Prerequisites

  • PHP 7.4 or newer and Composer 2.9+ β€” for the test suite only. The lock file was generated with Composer's plugin API 2.9 (plugin-api-version in composer.lock), so an older Composer refuses to install it.
  • PHPUnit 9.6 needs the bundled extensions dom, mbstring, xmlwriter, libxml and filter enabled; without them composer install fails on a dependency check before a single test runs.
  • bench.php itself has zero runtime dependencies: no vendor/ directory, no autoloader, no Composer. composer.json, composer.lock and everything they install into vendor/ are development tooling only; the shipped artifact stays the single, copy-paste deployable bench.php.
  • The suite writes to sys_get_temp_dir() (temporary files and the single-run lock) and starts a short-lived built-in PHP server on a free local port.
  • Optional: BENCH_PHP74=/path/to/php7.4 makes the suite lint bench.php with a real PHP 7.4 interpreter instead of trusting the static blocklist. Without it β€” and when the host is PHP 8.0+ β€” that single test is reported as skipped with the reason; it is never faked.
  • Child-process liveness is probed with posix_kill() when the extension is available, otherwise through /proc. On a platform that offers neither, the liveness test and its guard are skipped and say so.

Run on the host

composer install
vendor/bin/phpunit

Run inside DDEV

This checkout's DDEV configuration (.ddev/, PHP 7.4) pins the minimum version the script promises to support. Note that .ddev/ is listed in .gitignore, so a fresh clone may not contain it; in that case use the host commands above.

ddev start                # only needed if the project is not running yet
ddev composer install
ddev exec vendor/bin/phpunit

What the suite covers

  • Static contract β€” host php -l, declare(strict_types=1), no PHP 8-only syntax (blocklist), a real 7.4 lint when BENCH_PHP74 is set, no microtime() / output buffering / anonymous classes, and escaping through ENT_QUOTES | ENT_SUBSTITUTE.
  • JSON CLI contract β€” 21 rows, exactly 7 documented keys per row in the documented order, ops_per_sec === count / seconds, scale fallback and clamping with proportionality across runs, and total/budget accounting (a relationship, not a wall-clock threshold).
  • In-process API β€” BENCH_NO_AUTORUN includes the class silently, a throwing test becomes an error row with ops_per_sec: 0, hostile test names are escaped in HTML, and invalid UTF-8 stays visible without breaking the page.
  • HTTP behaviour β€” BENCH_TOKEN yields 403 on a missing or wrong token, a held lock yields 409 with Retry-After: 30, ?private=1 and BENCH_PRIVATE=1 mask the OS string, security headers are present, and the HTML report has one row per test.
  • Hygiene β€” no phpbench_* / benchtest_* temporary files survive the run, no built-in server outlives the HTTP class, and the temp baselines are captured before the first test, so class order (--order-by=random) cannot make them vacuous.

Current numbers

Observed on the author's machine only (they are not a target and vary by hardware): ~5 s for the whole suite on PHP 7.4 under DDEV, 13–17 s on the PHP 8.5 host, where most of the time is the two full CLI benchmark runs plus the HTTP scenarios. The suite asserts relationships and status codes, never wall-clock thresholds or a fixed assertion count, so slower hardware simply makes it slower.

The concurrency test takes the same advisory lock as the script. Its path can be reproduced with:

sys_get_temp_dir() . '/phpbench_lock_' . substr(sha1(<absolute path to bench.php>), 0, 12) . '.lock'

πŸ“Š Sample Results

Measured with scale=1.0 on the author's VPS β€” 4 vCPU (AMD EPYC), 8 GB RAM, PHP 8.3 CLI, OPcache on, JIT off, Xdebug disabled, 21 tests:

  • Math: 0.3149 s (254,049 ops/s)
  • String: 0.0539 s (148,386 ops/s)
  • Loops: 0.4541 s (44,039 ops/s)
  • Total Time: 4.8411 s β€” within the 15 s budget

The total time is compared against a 15 s budget ceiling and shown as a within budget / over budget badge; if max_execution_time is set and the run uses more than 80% of it, a warning row is rendered as well. Timings on Xdebug-enabled hosts are much higher β€” use XDEBUG_MODE=off before comparing anything with the numbers above.

πŸ“„ License

This project is open-source and available under the MIT License.

About

Advanced PHP Benchmark v1.0

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages