开发者

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

开发者 https://www.devze.com 2023-04-11 14:56 出处:网络
I don\'t know if the title is correct, anyway here is what I need: This is my code: $start = microtime();

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-&g开发者_运维问答t;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?


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.


afuzzyllama's answer is one way using a variable. You could also capture the foreach loop's output into a buffer, echo the time, then output from the buffer:

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

ob_start();
foreach($matches->fetchAll() as $match) {
    [..]
}
$table = ob_get_contents();
ob_end_clean();

$end = microtime();
$time = $end - $start;
echo "Done in: " . round($GLOBALS['time'], 4);
echo $table;

Also, I don't know why you're using $GLOBALS['time'] here.


Can't you just calculate the time using microtime before the foreach too? e.g.

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

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

精彩评论

暂无评论...
验证码 换一张
取 消