Created
April 2, 2019 13:23
-
-
Save alexstandiford/e82a94a0859d1ff1c800ad6581298407 to your computer and use it in GitHub Desktop.
Handy little snippet to get benchmark time for a function
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 | |
/** | |
* Calculates the time needed to run the specified function. | |
* @param $function string The callback to run. | |
* @param $function_args array Array of arguments to pass. | |
* @param int $number_of_times int The number of times this function should run. | |
* @return array containing the following information for each benchmark: | |
* $benchmark_time float The amount of time this benchmark took to run | |
* $total_time float The total amount of time it has taken to run this function | |
* so-far | |
* $result mixed The returned result of the called function | |
*/ | |
function get_time_to_run_function( $function, $function_args, $number_of_times = 1 ) { | |
$benchmarks = array(); | |
$start = microtime( true ); | |
$i = 0; | |
while( $i < $number_of_times ){ | |
$current = microtime( true ); | |
$result = call_user_func_array( $function, $function_args ); | |
$time = microtime( true ); | |
$benchmarks[] = array( 'benchmark_time' => $time - $current, 'total_time' => $time - $start, 'result' => $result ); | |
$i ++; | |
} | |
return $benchmarks; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment