Search code examples
phpmicrotime

How do I print the timing of a for loop before the output of the loop?


I don't know if the title is correct, anyway here is what I need:

This is my code:

$start = microtime();
$string = $_POST['string'];
$matches = $SQL->prepare("SELECT * FROM `users` WHERE `name` LIKE ?");
$matches->execute(array('%'.$string.'%'));

echo "Done in: " . round($_GLOBALS['time'], 4);
foreach($matches->fetchAll() as $match) {
    [..]
}
$end = microtime();
$time = $end - $start;

As you can see, I'm measuring the time of the query + displaying records, microtime() needs to be at the bottom of the foreach but I need to display the measured time ($time variable) before a foreach. As you can see I've tried to do this like this: echo "Done in: " . round($_GLOBALS['time'], 4); but it always is returning 0 (null).

What should I do?


Solution

  • You should do something like this:

    $start = microtime(true);
    $string = $_POST['string'];
    $matches = $SQL->prepare("SELECT * FROM `users` WHERE `name` LIKE ?");
    $matches->execute(array('%'.$string.'%'));
    
    $output = '';
    foreach($matches->fetchAll() as $match) {
        $output .= $someText;
        [...]
    }
    
    $end = microtime(true);
    $time = $end - $start;
    echo "Done in: " . round($time, 4);
    echo $output;
    

    Also, note I am using the optional parameter of true because this returns the time as a decimal number instead of two parts as the documentation states.