How to calculate runtime in PHP

Asked

Viewed 1,343 times

3

I would like to know how long it takes for a certain function, loop loop, etc... to be executed. I use the function microtime(), but I am a little lost to know exactly what time was spent. And my doubts are as follows:

1- How can I convert microseconds into seconds? So that it becomes somewhat readable and if you have a sense of the time that was spent during execution.

<?php

   $tempoInicial = round(microtime(true) * 1000);

   $var = 100000;

   for ($i=0; $i < $var; $i++) { 
      echo "$i -> ";
   }

   $tempoFinal = round(microtime(true) * 1000);

   $total = $tempoFinal - $tempoInicial;

   echo "Resultado: Tempo inicial: $tempoInicial <br> Tempo final: 
   $tempoFinal <br> Total: $total";

2- Is there any tool or resource available for PHP that can check in real time something like the execution speed of the script, of a function, loop, etc.

  • 3

    microtime(true) returns something like 1572433011.7642 (number of seconds plus fractions of seconds). By multiplying by 1000 and rounding, you get the amount of milliseconds (in case, 1572433011764), then to get in seconds, just divide by 1000. That’s it?

2 answers

1

Microsecond (Ms) is a multiple of the second, a unit of time, prefixed by the micro (µ) multiplier base patterns, equal to 0.000001 seconds(1 microsecond = 1.0E-6 seconds). So, to get the time in seconds, you must divide by 1000000.

From the PHP 5 you can use microtime at the beginning and end of your code:

<?php
    $inicio = microtime(true);
    sleep(1);
    $fim = microtime(true);
    $tempo = $fim - $inicio;
    printf("Processado em: %0.16f segundos", $tempo/1000000);
?>

See working: https://paiza.io/projects/udZy3WdDvQ4kYrUj7AGSSQ

From the PHP 5.4.0 , there is no need to start the start time, the $_SERVER["REQUEST_TIME_FLOAT"] already owns it:

<?php
    sleep(1);
    $tempo = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
    printf("Processado em: %0.16f segundos", $tempo/1000000);
?>

See Working: https://paiza.io/projects/JhDm9gJcBiFOu7hL_4ydtg

References

Microsecond to Seconds Conversion Calculator

Documentation microtime PHP

How to find php runtime?

  • 1

    You don’t want to put it anywhere like the PHP sandbox?

-2

Utilize time() instead of microtime()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.