PHP code example of sbwerewolf / stopwatch

1. Go to this page and download the library: Download sbwerewolf/stopwatch 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/ */

    

sbwerewolf / stopwatch example snippets


echo 'Duration is ' .
    (new \SbWereWolf\Stopwatch\HRTimeStopwatch())
    ->start()->stop()->getLastTime()->asNanoSeconds() .
    ' ns' .
    PHP_EOL;

$stopwatch = new SbWereWolf\Stopwatch\HRTimeStopwatch();
echo (new DateTimeImmutable())->format('s.u') . PHP_EOL;

$stopwatch->start();
time_nanosleep(0, 100);
$stopwatch->stop();

echo (new DateTimeImmutable())->format('s.u') .
    ' Period 1 duration: ' .
    $stopwatch->getLastTime()->asNanoSeconds() .
    ' ns' .
    PHP_EOL;

time_nanosleep(0, 100);

$stopwatch->start();
time_nanosleep(0, 100);
$stopwatch->stop();

echo (new DateTimeImmutable())->format('s.u') .
    ' Period 2 duration: ' .
    $stopwatch->getLastTime()->asNanoSeconds() .
    ' ns' .
    PHP_EOL;

/* Summa of all time periods */
echo (new DateTimeImmutable())->format('s.u') .
    ' Periods 1 + 2 summary duration: ' .
    $stopwatch->getSummaryTime()->asNanoSeconds() .
    ' ns' .
    PHP_EOL;

/* Overall time */
echo (new DateTimeImmutable())->format('s.u') .
    ' Whole process duration: ' .
    $stopwatch->getWholeTime()->asNanoSeconds() .
    ' ns' .
    PHP_EOL;

$stopwatch = new SbWereWolf\Stopwatch\HRTimeStopwatch();
$benchmark = new SbWereWolf\Stopwatch\Benchmark($stopwatch);

$delay = 100;
echo "Variable value before step z callback `$delay`" . PHP_EOL;
/* Variable value before step z callback `100` */
$benchmark->step('z', function () use ($delay) {
    time_nanosleep(0, $delay);
    $delay++;
});
echo "after step z callback `$delay`" . PHP_EOL;
/* after step z callback `100` */
/* Variable does not change its value */

$benchmark->step('x', function () use (&$delay) {
    time_nanosleep(0, $delay);
    $delay += 999;
});
echo "after step x callback `$delay`" . PHP_EOL;
/* after step x callback `1099` */
/* Variable does change its value */

$benchmark->step('c', function () use (&$delay) {
    $delay -= 999;
    time_nanosleep(0, $delay);
});
echo "after step c callback `$delay`" . PHP_EOL;
/* after step c callback `100` */
/* Variable does change its value */

echo "Benchmark steps measurement is:" . PHP_EOL;
$i=0;
foreach ($benchmark->report() as $desc => $val) {
    /** @var SbWereWolf\Stopwatch\ITimerReadings $val */
    echo "$desc => {$val->asNanoSeconds()} ns" . PHP_EOL;
    $i++;
}

$totalNanoseconds = $benchmark->total()->asNanoSeconds();
echo "Total is $totalNanoseconds ns";