0

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?

Udo E.
  • 2,665
  • 2
  • 21
  • 33

2 Answers2

0

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;
}
Udo E.
  • 2,665
  • 2
  • 21
  • 33
-1

microtime ([ bool $get_as_float = FALSE ] ) : mixed try set it to TRUE

From my point of view next happening. You get result in form "msec sec" and use only msec. When Time of execution more that ~500msec. Result is negative

If you don't want use float than use next approach

$start_time = explode(" ", $raw_start_time)[1] * 1000 + explode(" ", $raw_start_time)[0];

and same thing with end_time.

If microtime(FALSE) you will NOT get microseconds. Only millis. Micros woth TRUE

DuhVir
  • 447
  • 1
  • 4
  • 15
  • I want to avoid the use of decimal points in the result as much as possible. I want whole number microsecond value. – Udo E. Sep 29 '19 at 08:21
  • As far as I know there is no PHP function that returns MICROseconds not as real value. And that's pretty logical. Because it's very long "int" – DuhVir Sep 29 '19 at 08:30
  • Look also at `gettimeofday` maybe that's what you need – DuhVir Sep 29 '19 at 08:42