almasmurad/stopwatch

Component for measuring code execution time

0.4.4 2024-04-29 14:36 UTC

This package is auto-updated.

Last update: 2024-04-29 14:37:33 UTC


README

PHP tool that measures code execution time.

README in Russian

Usage

// create Stopwatch
$stopwatch = new Almasmurad\Stopwatch\Stopwatch();

// start measuring the first step
$stopwatch->start('code section #1');
//...

// start measuring the second step
$stopwatch->step('code section #2');
//...

// start measuring the third step
$stopwatch->step('code section #3');
//...

// finish measuring
$stopwatch->finish();

// output the report
$stopwatch->report();

As a result, the following report gets into the standard output:

 Start           | 06:55:14.123 
-----------------|--------------
 code section #1 |      0.198 s 
 code section #2 |      0.209 s 
 code section #3 |      1.200 s 
-----------------|--------------
 Summary         |      1.607 s 

Minimal Usage

$stopwatch = new Almasmurad\Stopwatch\Stopwatch();

//... (measured code)

$stopwatch->report();

As a result, the following report gets into the standard output:

 Start   | 06:55:14.123 
---------|--------------
 Summary |      0.198 s 

Output Report to File

$stopwatch->reportToFile(__DIR__.'/report.txt');

Report will be written to a file, and nothing will get into the standard output. If the file already exists, the report will replace its contents. In order for the report to append the contents of the file, use another method:

$stopwatch->reportToFileInAppendMode(__DIR__.'/report.txt');

Access to the Report Components

Instead of outputting the report to a standard stream or file, you can access its components:

// getting the report object
$report = $stopwatch->getReport();

// general indicators
$start   = $report->getStart()->getTimestamp();   // stopwatch start time
$finish  = $report->getFinish()->getTimestamp();  // stopwatch finish time
$elapsed = $report->getElapsed()->getSeconds();   // time of the entire stopwatch operation

// indicators of first code section 
$step1_start   = $report->getStepByIndex(0)->getStart()->getTimestamp();   
$step1_finish  = $report->getStepByIndex(0)->getFinish()->getTimestamp();  
$step1_elapsed = $report->getStep('code section #1')->getElapsed()->getSeconds();

// all of code sections
foreach ($report->getSteps() as $step){
    //...
}

You can read more about the report object in the section 'Report object'

Learn More