How can we get the execution time of a script? [duplicate]

5

Looking at the Comparing with DateTime class, is the date function more performative? and I did some testing with Daniel Omine's response , but I got results that did not seem to me to be reliable.

How can I get the runtime of a PHP script?

    
asked by anonymous 30.08.2016 / 11:54

2 answers

5

The microtime() function returns the current timestamp . You can use it to "mark" the start and end time of your script in order to get the runtime.

Here's an example:

<?php
// Armazena o timestamp antes da execucao do script
$tm_inicio = microtime( true ); 

//
// Codigo Script 
//

// Armazena  o timestamp apos a execucao do script
$tm_fim = microtime( true );

// Calcula o tempo de execucao do script 
$tempo_execucao = $tm_fim - $tm_inicio;

// Exibe o tempo de execucao do script em segundos
echo '<b>Tempo de Execucao:</b> '.$tempo_execucao.' Segs';

?>

Reference:

link

I hope I have helped!

    
30.08.2016 / 12:27
0

In the example of the other answer I used this:

class Bench
{

    protected static $ini;

    public static function Start($id = 0)
    {
        /*
        Get the start time in microseconds, as a float value
        */
        self::$ini[$id] = microtime(true);
    }

    public static function Calc($id = 0)
    {
        /*
        Get the difference between the start and the end time in microseconds, as a float value
        */
        $end = microtime(true);
        $diff = $end - self::$ini[$id];

        /*
        Break the difference into seconds and microseconds
        */
        return array($diff, $diff - intval($diff), self::$ini[$id], $end);
    }

}

How to use

// Inicia a contagem. Após essa linha não pode ter nada que não seja relacionado ao que deseja testar.
Bench::Start();

// aqui o bloco de script que deseja testar

// Finaliza a contagem e retorna o resultado.
$bench = Bench::Calc();
echo '<pre>';
print_r($bench);
echo '</pre>';

It's important to note that you got an unexpected result because of this ceiling of the return method Calc()

return array($diff - intval($diff), self::$ini[$id], $end);

This is the original return because I usually do tests that return less than 1 second. usually 1000 to 100 thousand iterations. So I do not need to know how many seconds.

For your case, where you applied 1 million iterations, return this way:

return array(
    $diff, // literal
    $diff - intval($diff), // parte decimal
    self::$ini[$id], // microtime inicial
    $end // microtime final
);

In the first key, the value in seconds.

Note: Be aware that tests are within the context of the original question: Comparing with DateTime class, date Is it more performative?

    
30.08.2016 / 13:01