Tag Archive: code


How to measure execution time in PHP

While working with José ABCD (that’s not his last name… he likes to remain unknown) we were talking about two ways of solving a problem un PHP and which would be the best in terms of speed. To solve this, we decided to use microtime(). This is what we did:
Code


          $cicles = 5000; // Number of cicles

          $totalTime = 0; // Total time, set to 0
          for ($i=0; $i<$cicles; $i++){ // This for gets run for $cicles times
               $timeInit = microtime(); // Initial time
                    ## código a probar aquí ## // This is the code to test, it can be a function or several lines of code
               $timeEnd = microtime(); // End time
                    // Next we process time to get a total amout of time during all $cicles
               $timeInit = explode(" ", $timeInit);
               $timeInit = (double) $timeInit[0] + $timeInit[1];
               $timeEnd = explode(" ", $timeEnd);
               $timeEnd = (double) $timeEnd[0] + $timeEnd[1];
               $totalTime += ($timeEnd - $timeInit);
          }
          $timeAvg = $totalTime / $cicles; // Average time
                    // We print our results
          echo "<div>";
          echo "Total = ".$totalTime."<br>";
          echo "Avg = ".$timeAvg."<br>--<br>";
          echo "</div>";

Con José ABCD (no es su apellido real… le gusta el anonimato) estábamos conversando sobre dos formas de solucionar un problema en PHP y cuál sería más eficiente. Para resolver el problema, decidimos usar microtime(). Lo que hicimos a continuación con un ejemplo:
Code


          $cicles = 5000; // Cantidad de ciclos

          $totalTime = 0; // Tiempo total, inicialmente 0
          for ($i=0; $i<$cicles; $i++){ // Este for es ejecutado $cicles veces
               $timeInit = microtime(); // Tiempo inicial
                    ## código a probar aquí ## // Este es el código a probar, puede ser una función o varias líneas de código
               $timeEnd = microtime(); // Tiempo final
                    // Se procesa el tiempo para obtener el total durante todos los ¢cicles
               $timeInit = explode(" ", $timeInit);
               $timeInit = (double) $timeInit[0] + $timeInit[1];
               $timeEnd = explode(" ", $timeEnd);
               $timeEnd = (double) $timeEnd[0] + $timeEnd[1];
               $totalTime += ($timeEnd - $timeInit);
          }
          $timeAvg = $totalTime / $cicles; // Average time
                    // Se muestran los resultados
          echo "<div>";
          echo "Total = ".$totalTime."<br>";
          echo "Avg = ".$timeAvg."<br>--<br>";
          echo "</div>";
Powered by WordPress and Motion by 85ideas.