Skip to content

Instantly share code, notes, and snippets.

@mishterk
Created May 7, 2018 23:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/8c93148cbb9a827829d2b5092105c959 to your computer and use it in GitHub Desktop.
Save mishterk/8c93148cbb9a827829d2b5092105c959 to your computer and use it in GitHub Desktop.
<?php
/**
* Class BenchMarker
* @author Phil Kurth <phil@philkurth.com.au>
*
* A simple benchmarking utility. Easiest way to use this:
*
* BenchMarker::start();
*
* … run stuff here …
*
* BenchMarker::log('Testing xxx functionality');
*
*/
class BenchMarker {
public static $starting_memory = 0;
public static $starting_time = 0;
public static $finishing_memory = 0;
public static $finishing_time = 0;
/**
* Starts the tests
*/
public static function start() {
self::$starting_memory = memory_get_usage();
self::$starting_time = microtime( true );
}
/**
* @param string $note Optional note to output above the results
*/
public static function log( $note = '' ) {
self::finish();
if ( $note ) {
echo $note . "\n";
}
self::print();
self::start();
}
/**
* Use this if you need to capture the output instead of printing it.
*
* @param string $note See self::log()
*
* @return string
*/
public static function capture( $note = '' ) {
ob_start();
self::log( $note );
return ob_get_clean();
}
/**
* Logs stats at end of test
*/
public static function finish() {
self::$finishing_memory = memory_get_usage();
self::$finishing_time = microtime( true );
}
/**
* Prints test output
*/
public static function print() {
$execution_time = self::$finishing_time - self::$starting_time;
$memory_used = self::$finishing_memory - self::$starting_memory;
$output = "Time:\t\t\t %0.12f seconds \n";
$output .= "Memory (raw):\t\t %d bytes \n";
$output .= "Memory:\t\t\t %s \n";
$output .= "Peak Memory:\t\t %s \n";
$output .= "Memory Limit:\t\t %s \n";
$output .= "\n\n";
printf( $output,
$execution_time,
$memory_used,
self::format_bytes( $memory_used ),
self::format_bytes( memory_get_peak_usage() ),
self::format_bytes( self::get_memory_limit() )
);
}
/**
* @param $size
*
* @return string
*/
private static function format_bytes( $size ) {
$unit = array( 'b', 'kb', 'mb', 'gb', 'tb', 'pb' );
return @round( $size / pow( 1024, ( $i = floor( log( $size, 1024 ) ) ) ), 2 ) . ' ' . $unit[ $i ];
}
/**
* Get memory limit
*
* @return int
*/
private static function get_memory_limit() {
if ( function_exists( 'ini_get' ) ) {
return ini_get( 'memory_limit' );
}
return '?';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment