Stopwatch for Search Results - how?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Stopwatch for Search Results - how?

Post by simonmlewis »

Hi

I don't know if this is a PHP query or a Javascript query. So I apologise if this is in the wrong place.

I want to provide users with the ability to see how long a PHP MySQL Query took to run. You see it in Google and some other sites.

ie. Your search took 0.256 seconds to complete.

It's fairly pointless - but I would like to add it if anyone knows a simple method - if PHP has a useful built-in tool ???

Simon
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Stopwatch for Search Results - how?

Post by Darhazer »

Before query (or in the very beginning of the script):

Code: Select all

$start = microtime(true);
After query (or in the end of the script):

Code: Select all

$end = microtime(true);
And for displaying:

Code: Select all

echo sprintf('Your query took %s seconds to complete', ($end - $start));
Some formatting and you are ready :)
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Stopwatch for Search Results - how?

Post by simonmlewis »

Excellent stuff.
I am trying ot round it down to about 3 or 4 decimal places with this:

Code: Select all

echo round($end,2); 
But don't see a way to input that into the code you provided.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Stopwatch for Search Results - how?

Post by AbraCadaver »

Something like this:

Code: Select all

$start = microtime(true);
// do something
$stop = microtime(true);
$elapsedtime = $stop - $start;

printf("Something took %f seconds", $elapsedtime);
I use functions, and if you need it across pages then you can use sessions:

Code: Select all

session_start();

timer_start();
// do something
timer_stop();

function timer_start() {
	$_SESSION['start'] = microtime(true);
}

function timer_stop($display=true) {
	$stop = microtime(true);
	$_SESSION['elapsed'] = $stop - $_SESSION['start'];
	
	if($display) {
		printf("Something took %f seconds", $_SESSION['elapsed']);
	}
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply