Created
January 25, 2018 09:19
-
-
Save pieterbeulque/f2667d3900d19c120c6ab06a90aa8536 to your computer and use it in GitHub Desktop.
Easily measure PHP performance timing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Little helper class to help you measure server performance | |
* | |
* Usage: | |
* $stopwatch = new Stopwatch(); | |
* $stopwatch->start('My expensive operation'); | |
* // Do expensive operation | |
* $stopwatch->stop(); | |
* | |
* $stopwatch->start('My other expensive operation'); | |
* $stopwatch->stop('My other expensive operation'); | |
* | |
* $stopwatch->read(); | |
* | |
* Note: you can also pass this through to your Timber context | |
* $context['stopwatch'] = $stopwatch; | |
* & use it like {{ stopwatch.start('Render expensive part') }} | |
*/ | |
class Stopwatch { | |
public function __construct() { | |
$this->entries = array(); | |
} | |
public function start( $label ) { | |
$key = sanitize_title( $label ); | |
$this->entries[ $key ] = array( | |
'label' => $label, | |
'start' => microtime( true ), | |
'end' => null, | |
); | |
} | |
public function stop( $label ) { | |
$key = sanitize_title( $label ); | |
if ( isset( $this->entries[ $key ] ) ) { | |
$this->entries[ $key ]['end'] = microtime( true ); | |
} | |
} | |
public function read() { | |
$header = array(); | |
foreach ( $this->entries as $key => $value ) { | |
$start = $value['start']; | |
if ( ! $start ) { | |
continue; | |
} | |
$label = $value['label'] ?? $key; | |
$end = $value['end'] ?? microtime( true ); | |
$duration = ( $end - $start ) * 1000; | |
array_push( $header, sprintf( '%s=%f; "%s"', $key, $duration, $label ) ); | |
} | |
header( 'Server-Timing: ' . join( $header, ',' ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment