Jeff
Jeff

Reputation: 6130

PHP benchmark functions timer script

I have two functions whose execution time I would like to compare:

function subject_one() {
    $str = preg_match_all( ...[SNIP]... );
    // ...[SNIP]...
    return $str;
}

function subject_two() {
    $reader = new XMLReader;
    $writer = new XMLWriter;
    // ...[SNIP]...
    echo $str;
}

Is it possible to write a function to do this?

For example:

function benchmark_two_functions( $first_function, $second_function ) {
    // do stuff
    return $length_of_time_to_complete_each_function
}

Most examples I've seen add code to the top and bottom of the script, which I'd like to avoid, if possible.

Upvotes: 5

Views: 779

Answers (3)

vdrmrt
vdrmrt

Reputation: 872

Try this

function subject_one(){
    sleep(1);
}

function subject_two(){
    sleep(5);
}

/* Result should be ~4 */
print benchmark_two_functions('subject_one','subject_two');

function getmicrotime() { 
    list($usec, $sec) = explode(" ",microtime()); 
    return ((float)$usec + (float)$sec);
}

function benchmark_two_functions($first_function, $second_function){
    $start = getmicrotime();
    $first_function();
    $exec_time_first = getmicrotime() - $start;

    $start = getmicrotime();
    $second_function();
    $exec_time_second = getmicrotime() - $start;

    return $exec_time_first - $exec_time_second;
}

Upvotes: 11

Björn
Björn

Reputation: 29411

PEAR has a Benchmark library for PHP profiling. It works pretty well, but maybe XDebug is a better tool if you have root access to your server and can install it.

Upvotes: 0

dusoft
dusoft

Reputation: 11469

maybe TICKS could be used?

http://sk2.php.net/manual/en/function.register-tick-function.php

Upvotes: 0

Related Questions