mts7 / benchmarks
PHP 性能基准
3.0.2
2024-06-18 21:43 UTC
Requires
- php: ^8.2
- mts7/php-dependency-injection: ^1
- mts7/php-execution-timer: ^1
Requires (Dev)
- mts7/php-code-quality: ^0.1.19
- phpunit/phpunit: ^10.5
- roave/security-advisories: dev-latest
README
一个用于基准测试简单功能的框架
安装
composer require --dev mts7/Benchmarks --prefer-dist
使用
Benchmarks 包含一个用于依赖注入的 容器,这使得设置基准测试更快、更简单。
$container = \MtsBenchmarks\Factory\ContainerFactory::create();
单方法调用
run
方法接受一个可调用对象数组,并会对每个可调用对象执行指定次数的迭代,同时为当前迭代提供一个参数。通过使用 run
方法,所有必要的基准测试步骤都按照正确的顺序包含在内。
调用 run
后,任何报告类都可以接受结果并处理。
$samples = 5; $iterations = 100; $title = 'callable name'; $benchmark = $container->get(\MtsBenchmarks\Benchmark::class, [ $container->get(\MtsBenchmarks\Helper\IncrementIntegerIterator::class, [$samples]), $container->get(\MtsBenchmarks\Helper\IncrementIntegerIterator::class, [$iterations]), ] ); $results = $benchmark->run(['callable']); $report = $container->get(\MtsBenchmarks\Report\ConsoleReport::class); echo $report->generate($samples, $iterations, $title, $results);
多次方法调用
在这种情况下,框架提供的是每个可调用对象的时间计算结果,而不是原始数据。输出格式化由报告对象处理。
$samples = 5; $iterations = 100; $title = 'callable name'; $benchmark = $container->get(\MtsBenchmarks\Benchmark::class, [ $container->get(\MtsBenchmarks\Helper\IncrementIntegerIterator::class, [$samples]), $container->get(\MtsBenchmarks\Helper\IncrementIntegerIterator::class, [$iterations]), ] ); $report = $container->get(\MtsBenchmarks\Report\ConsoleReport::class); $output = $report->buildTitle($samples, $iterations, $title); $output .= $report->buildHeaders($title); $results = $benchmark->run(['callable']); $output .= $report->buildResults($results); echo $output;
当只有一个可调用对象需要检查或希望独立测试每个可调用对象时(不使用框架),buildSamples
将会工作。这是调用可调用对象并设置计时的内部方法。
// raw durations from executing the callable $iterations times per sample $durations = $benchmark->buildSamples('callable');
比较
框架会显示用户哪些测试主题比其他主题更快,以及快多少,这意味着这是一个有用的比较工具,而不是计时工具。
虽然框架处理测试主题的计时和执行,但它不处理测试主题的创建或组织。由于每个系统都不同,因此没有任何基准测试在系统之间有恒定的时间。
在 MacBook Pro M1 Pro 上,一些基准测试的时间比使用该框架较小版本运行的时间长 2.5 倍。在相同系统上的基本基准测试时间比在 PHP Sandbox 上执行的时间长 2 倍。
未来增强
- 提高速度/性能
- 添加额外的报告选项(如 HTML、XML)
- 在 ConsoleReport 输出中添加计时和内存使用情况
- 允许基准测试函数具有任意数量的参数,而不是仅要求 int 类型的参数
包含的基准测试
注意,这些基准测试不包括在发行包中,只可在源代码中获取。
composer require --dev mts7/Benchmarks --prefer-source
所有这些基准测试都可以通过运行 php benchmarks/{file-name}.php
来执行。