PHP code example of mts7 / php-execution-timer

1. Go to this page and download the library: Download mts7/php-execution-timer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mts7 / php-execution-timer example snippets


$timer = new \MtsTimer\Timer();
$timer->start();
doSomething();
$timer->stop();
echo 'Duration: ' . $timer->getDuration() . PHP_EOL;

$timer = new \MtsTimer\Timer();
for ($i = 0; $i < 5; $i++) {
    $timer->start();
    doSomething();
    $timer->stop();
    echo 'Something took ' . $timer->getDuration() . ' seconds.' . PHP_EOL;
}
echo 'Total duration: ' . $timer->getTotalDuration() . PHP_EOL;

$timer = new \MtsTimer\Timer();
$timings = [];
for ($i = 0; $i < 3; $i++) {
    $timer->reset();
    for ($j = 0; $j < 5; $j++) {
        $timer->start();
        doSomething();
        $timer->stop();    
    }
    $timings[] = $timer->getTotalDuration();
}

class Benchmark
{
    public function __construct(private \MtsTimer\TimerInterface $timer)
    {
    }

    public function run(callable $callable): float
    {
        $this->timer->start();
        $callable();
        $this->timer->stop();
        
        return $this->timer->getDuration();
    }
}

class RunTheBenchmark
{
    public function execute(): float
    {
        $timer = new \MtsTimer\Timer();
        $benchmark = new Benchmark($timer);
        return $benchmark->run([self::class, 'doNothing']);
    }
    
    public static function doNothing(): void
    {
    }
}

class BenchmarkTest
{
    public function testRun(): void
    {
        $timer = new \MtsTimer\FixedTimer();
        $benchmark = new Benchmark($timer);

        $duration = $benchmark->run([RunTheBenchmark::class, 'doNothing']);
        
        $this->assertSame($timer::DURATION, $duration);
    }
}
shell
composer