Page 1 of 1

Stopwatch for Search Results - how?

Posted: Tue Jun 29, 2010 2:08 pm
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

Re: Stopwatch for Search Results - how?

Posted: Tue Jun 29, 2010 2:34 pm
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 :)

Re: Stopwatch for Search Results - how?

Posted: Tue Jun 29, 2010 2:40 pm
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.

Re: Stopwatch for Search Results - how?

Posted: Tue Jun 29, 2010 2:43 pm
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']);
	}
}