Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions .github/workflows/benchmark.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

const THRESHOLD = 0.10;

function results(string $file): array
{
$results = array();
foreach(simplexml_load_file($file)->xpath('//variant') as $variant) {
$class = (string)$variant->xpath('ancestor::benchmark')[0]['class'];
$name = substr($class, strrpos($class, '\\') + 1);
$results[$name][(string)$variant->{'parameter-set'}['name']] = (float)$variant->stats['mode'];
}

return $results;
}

function duration(float $microseconds): string
{
return match(true) {
$microseconds < 1000 => sprintf('%.1f µs', $microseconds),
$microseconds < 1000000 => sprintf('%.1f ms', $microseconds / 1000),
default => sprintf('%.2f s', $microseconds / 1000000),
};
}

function commit(string $ref, string $sha): string
{
return '<code>'.$ref.'</code> ('.substr($sha, 0, 7).')';
}

[, $baseFile, $headFile, $tableFile] = $argv;
$base = results($baseFile);
$head = results($headFile);

$counts = array();
$changes = array();
$ratios = array();
foreach($head as $benchmark => $cases) {
$counts[$benchmark] = array('improved' => 0, 'regressed' => 0, 'untouched' => 0, 'new' => 0);
foreach($cases as $case => $time) {
if(false === isset($base[$benchmark][$case])) {
$counts[$benchmark]['new']++;
continue;
}
$efficiency = $base[$benchmark][$case] / $time - 1;
if(abs($efficiency) < THRESHOLD) {
$counts[$benchmark]['untouched']++;
continue;
}
$counts[$benchmark][$efficiency > 0 ? 'improved' : 'regressed']++;
$changes[] = array($efficiency > 0 ? '⚡' : '❌', $benchmark.': '.$case, $base[$benchmark][$case], $time, $efficiency);
$ratios[] = 1 + $efficiency;
}
}
usort($changes, fn(array $a, array $b) => abs($b[4]) <=> abs($a[4]));

$impact = $ratios ? array_product($ratios) ** (1 / count($ratios)) - 1 : 0.0;
echo "<!-- benchmark -->\n";
echo match(true) {
!$ratios => '## Merging this PR will **not alter performance**',
$impact >= 0 => sprintf('## Merging this PR will **improve performance by %.2f%%**', 100 * $impact),
default => sprintf('## Merging this PR will **degrade performance by %.2f%%**', -100 * $impact),
}, "\n\n";

echo "| Benchmark | ⚡ improved | ❌ regressed | ✅ untouched | 🆕 new |\n";
echo "| --------- | ---------- | ----------- | ----------- | ------ |\n";
foreach($counts as $benchmark => $count) {
printf("| `%s` | %d | %d | %d | %d |\n", $benchmark, $count['improved'], $count['regressed'], $count['untouched'], $count['new']);
}

if($changes) {
echo "\n### Performance Changes\n\n";
echo "| | Benchmark | `BASE` | `HEAD` | Efficiency |\n";
echo "| --- | --------- | ------ | ------ | ---------- |\n";
foreach($changes as [$icon, $name, $before, $after, $efficiency]) {
printf("| %s | `%s` | %s | %s | %+.2f%% |\n", $icon, $name, duration($before), duration($after), 100 * $efficiency);
}
}

printf("\nA benchmark is changed when its efficiency (`BASE` / `HEAD` - 1) is at least %d%% in either direction.\n", 100 * THRESHOLD);
echo "\n<details><summary>All benchmarks</summary>\n\n```\n", rtrim(file_get_contents($tableFile)), "\n```\n\n</details>\n";
echo "\n---\n\n<sub>Comparing ", commit(getenv('HEAD_REF'), getenv('HEAD_SHA')), ' with ', commit(getenv('BASE_REF'), getenv('BASE_SHA')), "</sub>\n";
43 changes: 43 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,46 @@ jobs:
php vendor/bin/infection --static-analysis-tool=mago $DIFF
env:
BASE_REF: '${{ github.base_ref }}'

benchmark:
if: "github.event_name == 'pull_request'"
runs-on: 'ubuntu-latest'
permissions:
contents: 'read'
pull-requests: 'write'
steps:
- name: 'Checkout'
uses: 'actions/checkout@v4'
with:
fetch-depth: 0
- name: 'Install PHP'
uses: 'shivammathur/setup-php@v2'
with:
php-version: '8.5'
tools: 'composer:v2'
coverage: 'none'
- name: 'PHPBench'
shell: 'bash'
run: |
composer require --dev -W phpbench/phpbench
rm -rf src && git checkout "origin/$BASE_REF" -- src
php vendor/bin/phpbench run --tag=base --progress=none --dump-file=benchmark-base.xml
rm -rf src && git checkout HEAD -- src
php vendor/bin/phpbench run --ref=base --report=aggregate --progress=none --no-ansi --dump-file=benchmark-head.xml | tee benchmark.txt
BASE_SHA=$(git rev-parse "origin/$BASE_REF") php .github/workflows/benchmark.php benchmark-base.xml benchmark-head.xml benchmark.txt > benchmark.md
env:
BASE_REF: '${{ github.base_ref }}'
HEAD_REF: '${{ github.head_ref }}'
HEAD_SHA: '${{ github.event.pull_request.head.sha }}'
- name: 'Benchmark comment'
if: "github.event.pull_request.head.repo.full_name == github.repository"
run: |
ID=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate --jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith("<!-- benchmark -->"))) | .id' | tail -n 1)
if [ -n "$ID" ]; then
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$ID" -F body=@benchmark.md > /dev/null
else
gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body-file benchmark.md
fi
env:
GH_TOKEN: '${{ github.token }}'
PR: '${{ github.event.pull_request.number }}'
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ vendor
composer.lock
coverage
coverage.xml
.phpbench
9 changes: 9 additions & 0 deletions phpbench.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"$schema": "./vendor/phpbench/phpbench/phpbench.schema.json",
"runner.bootstrap": "vendor/autoload.php",
"runner.path": "tests/Benchmark",
"runner.file_pattern": "*Bench.php",
"runner.php_config": {
"memory_limit": "1G"
}
}
60 changes: 60 additions & 0 deletions tests/Benchmark/ParserBench.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php
namespace Thunder\Shortcode\Tests\Benchmark;

use PhpBench\Attributes\BeforeMethods;
use PhpBench\Attributes\Iterations;
use PhpBench\Attributes\ParamProviders;
use PhpBench\Attributes\Revs;
use PhpBench\Attributes\Warmup;
use Thunder\Shortcode\Parser\HybridParser;
use Thunder\Shortcode\Parser\ParserInterface;
use Thunder\Shortcode\Parser\RegexParser;
use Thunder\Shortcode\Parser\RegularParser;
use Thunder\Shortcode\Parser\WordpressParser;

#[BeforeMethods('setUp')]
#[Revs(1)]
#[Iterations(5)]
#[Warmup(1)]
final class ParserBench
{
private ParserInterface $parser;
private string $text;
private int $loops;

public function setUp(array $params): void
{
$this->parser = match($params['parser']) {
'regular' => new RegularParser(),
'regex' => new RegexParser(),
'hybrid' => new HybridParser(),
'wordpress' => new WordpressParser(),
};
$this->text = Texts::get($params['text'], $params['times']);
$this->loops = $params['loops'];
}

#[ParamProviders('provideCases')]
public function benchParse(): void
{
for($i = 0; $i < $this->loops; $i++) {
$this->parser->parse($this->text);
}
}

public function provideCases(): \Generator
{
$times = array('article' => 8, 'dense' => 60, 'nested' => 50, 'deep' => 10, 'brackets' => 200);
$loops = array(
'regular' => array('article' => 100, 'dense' => 50, 'nested' => 50, 'deep' => 5, 'brackets' => 10),
'regex' => array('article' => 2000, 'dense' => 200, 'nested' => 1000, 'deep' => 2000, 'brackets' => 10),
'hybrid' => array('article' => 2000, 'dense' => 200, 'nested' => 500, 'deep' => 200, 'brackets' => 200),
'wordpress' => array('article' => 2000, 'dense' => 500, 'nested' => 2000, 'deep' => 5000, 'brackets' => 20),
);
foreach($loops as $parser => $texts) {
foreach($texts as $text => $count) {
yield $parser.' '.$text => array('parser' => $parser, 'text' => $text, 'times' => $times[$text], 'loops' => $count);
}
}
}
}
71 changes: 71 additions & 0 deletions tests/Benchmark/ProcessorBench.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php
namespace Thunder\Shortcode\Tests\Benchmark;

use PhpBench\Attributes\BeforeMethods;
use PhpBench\Attributes\Iterations;
use PhpBench\Attributes\ParamProviders;
use PhpBench\Attributes\Revs;
use PhpBench\Attributes\Warmup;
use Thunder\Shortcode\HandlerContainer\HandlerContainer;
use Thunder\Shortcode\Parser\HybridParser;
use Thunder\Shortcode\Parser\RegularParser;
use Thunder\Shortcode\Processor\Processor;
use Thunder\Shortcode\Shortcode\ShortcodeInterface;

#[BeforeMethods('setUp')]
#[Revs(1)]
#[Iterations(5)]
#[Warmup(1)]
final class ProcessorBench
{
private Processor $processor;
private string $text;
private int $loops;

public function setUp(array $params): void
{
$handlers = new HandlerContainer();
$handlers->setDefault(function(ShortcodeInterface $s) {
return '<'.$s->getName().'>'.$s->getContent().'</'.$s->getName().'>';
});
$handlers->add('url', function(ShortcodeInterface $s) {
return '<a href="'.$s->getParameter('href').'">'.$s->getContent().'</a>';
});
$handlers->add('button', function(ShortcodeInterface $s) {
return '<a class="button '.$s->getParameter('color').'" href="'.$s->getParameter('url').'">'.$s->getContent().'</a>';
});
$handlers->add('img', function(ShortcodeInterface $s) {
return '<img src="'.$s->getParameter('src').'" alt="'.$s->getParameter('alt').'">';
});
$handlers->add('icon', function(ShortcodeInterface $s) {
return '<i class="icon-'.$s->getBbCode().'"></i>';
});

$parser = 'hybrid' === $params['parser'] ? new HybridParser() : new RegularParser();
$this->processor = new Processor($parser, $handlers);
$this->text = Texts::get($params['text'], $params['times']);
$this->loops = $params['loops'];
}

#[ParamProviders('provideCases')]
public function benchProcess(): void
{
for($i = 0; $i < $this->loops; $i++) {
$this->processor->process($this->text);
}
}

public function provideCases(): \Generator
{
$times = array('article' => 8, 'dense' => 250, 'nested' => 50, 'deep' => 1);
$loops = array(
'regular' => array('article' => 50, 'dense' => 2, 'nested' => 10, 'deep' => 2),
'hybrid' => array('article' => 200, 'dense' => 2, 'nested' => 50, 'deep' => 20),
);
foreach($loops as $parser => $texts) {
foreach($texts as $text => $count) {
yield $parser.' '.$text => array('parser' => $parser, 'text' => $text, 'times' => $times[$text], 'loops' => $count);
}
}
}
}
34 changes: 34 additions & 0 deletions tests/Benchmark/Texts.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
namespace Thunder\Shortcode\Tests\Benchmark;

final class Texts
{
private const PROSE = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.';
private const PROSE_UTF8 = 'Zażółć gęślą jaźń, pchnąć w tę łódź jeża lub ośm skrzyń fig. Świątecznie przyozdobiony żółty żuraw ćwiczył źrebięta na łące 🐎, a wąż Ździś łaził między łąkami, gdzie rósł bób. Grzegorz Brzęczyszczykiewicz z Chrząszczyżewoszyc wsiadł do pociągu, żeby dojechać na czas.';

public static function get(string $name, int $times): string
{
return str_repeat(match($name) {
'article' => self::PROSE.' This is [b]important[/b], so [url href="https://example.com/articles/42"]read more[/url].'."\n\n"
.self::PROSE_UTF8."\n\n"
.'[img src="/media/photo-42.jpg" alt="Zdjęcie 📷" /]'."\n\n"
.'[quote author="Grzegorz Brzęczyszczykiewicz"]'.self::PROSE.'[/quote]'."\n\n",
'dense' => '[button url="https://example.com/buy?id=42" color=blue size=large]Buy now[/button] [icon=star /] [tag]php[/tag] [img src=photo.jpg alt="A photo" width=640 /]'."\n",
'nested' => '[row][col width=6][card title="First card"][b]Bold[/b] and [i]italic[/i] text.[/card][/col][col width=6][card title="Second card"][url href="https://example.com"]A link[/url][/card][/col][/row]'."\n",
'deep' => self::deep(100),
'brackets' => 'As shown in the survey[1], most results [citation needed] were confirmed later[2]; see [the documentation](https://example.com/docs) for details. ',
}, $times);
}

private static function deep(int $depth): string
{
$open = '';
$close = '';
for($i = 1; $i <= $depth; $i++) {
$open .= '[d'.$i.']';
$close = '[/d'.$i.']'.$close;
}

return $open.'x'.$close."\n";
}
}
Loading