Mario G.
Mario G.

Reputation: 393

Count the time it takes to retrieve data from the database

I would measure how long it takes my script to retrieve data from the database so I wrote this code.

$Time = time();
$Content = mysql_query("SELECT * FROM table");

while($Row = mysql_fetch_array($Content)) {

$UserNick = $Row['UserNickname'];

echo "<div id=\"nickname_users\">".$UserNick."</div>";
$Time2 = time();
$Total = $Time-$Time2;
echo "he employed ".$Total." to retrieve data from the database";
}

But he returned 0, so i read "He employes 0 to retrieve data from the database. How can i fix?

Upvotes: 0

Views: 414

Answers (3)

will
will

Reputation: 1511

$start = microtime(true);
$query = mysql_query('SELECT * FROM `table`');

while ($row = mysql_fetch_array($query)) {
    $userNick = $row['UserNickName'];

    $total_employed_microseconds = microtime(true) - $start;
    $total_employed_seconds = $total_employed_microseconds * 1000000.0;

    echo "{$userNick} employed {$total_employed_microseconds} microseconds
          and {$total_employed_seconds}";
}

$end = microtime(true);
$total_microseconds = $end - $start;
$total_seconds = $total_microseconds * 1000000.0;

echo "It took {$total_microseconds} microseconds and {$total_seconds} seconds.";

Using microtime() will allow you to be more accurate with your results. You want to make sure you subtract the start from the end, since the end will always be a larger number. (don't use my variable names)

Upvotes: 0

vee
vee

Reputation: 38645

time returns integer, i.e. returns number of seconds since the Unix Epoch. Depending upon the complexity of your script it's very less likely that your code takes seconds to execute. It is however possible though.

A better solution in this case would be to use microtime which returns the current Unix timestamp with microseconds.

$Time = microtime(true);
$Content = mysql_query("SELECT * FROM table");

while($Row = mysql_fetch_array($Content)) {

$UserNick = $Row['UserNickname'];

echo "<div id=\"nickname_users\">".$UserNick."</div>";
$Time2 = microtime(true);
$Total = $Time2-$Time;
echo "he employed ".$Total." microseconds to retrieve data from the database";
}

Also, I believe you want $Time2-$Time not the other way around.

Upvotes: 1

user1864610
user1864610

Reputation:

The PHP function has a resolution of seconds, so if your query returns in less than a second you're likel to get zero as an answer

You should use microtime() instead, which has a resolution of microseconds (millionths of a second).

Upvotes: 0

Related Questions