Skip to content
Advertisement

Measuring the execution time of any piece of code in PHP, getting negative result

I’m trying to profile some piece of php code by computing the time in microseconds it takes it to execute. I have created a profiler function that take another function as parameter like this

function profiler($funct) 
{
    $raw_start_time = microtime();
    $funct();
    $raw_end_time = microtime();

    $start_time = 1000000 * (double) explode(" ", $raw_start_time)[0];
    $end_time = 1000000 * (double) explode(" ", $raw_end_time)[0];

    return $end_time - $start_time;
}

I use my profiler() function like this

$duration = profiler(function() {
                //code i want to profile
            });

echo $duration;

The function runs correctly most times and returns the correct time duration of execution. However, I get negative values in some test cases. What could be the problem?

Advertisement

Answer

Floating point arithmetic seems to be a hassle, so I’m trying to avoid it as much as possible.

The problem with the OP code was that only the microseconds part of the result was used. Consequently, if duration of the execution exceeds one second, the end result can be a negative difference.

The solution that worked for me was to substring the microseconds part (to eliminate the leading zero) and join that to the end of seconds part. Finally, everything is converted to microseconds by multiplying by 1000000.

function profiler($funct) 
{
    $raw_start_time = microtime();
    $funct();
    $raw_end_time = microtime();

    $array_start_time = explode(" ", $raw_start_time);
    $start_time = (int) (1000000 * (double) implode("", [$array_start_time[1], substr($array_start_time[0], 1, 8)]));

    $array_end_time = explode(" ", $raw_end_time);
    $end_time = (int) (1000000 * (double) implode("", [$array_end_time[1], substr($array_end_time[0], 1, 8)]));

    return $end_time - $start_time;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement