Nathan
Nathan

Reputation: 12010

Is there a way to put the number of seconds a script takes to execute (or "page load time") in the middle of the page?

I want to put the number of seconds a search script takes to search in PHP. But, I don't want to put that number at the bottom of the page. I put this at the top of the PHP file:

$time_start = microtime(true);

And then I put this where I am echoing out the number:

$time_end = microtime(true);
echo number_format($time_end - $time_start, 5);

The problem is that this doesn't count the whole script as there's still a lot of other code under that. Is there a way to determine how long it takes to execute but echo it in another place on the page rather than the bottom?

Upvotes: 1

Views: 58

Answers (2)

Another Code
Another Code

Reputation: 3151

I can think of three possibilities:

  • Echo the value inside a Javascript at the bottom of the page. The script can modify the DOM as soon as the page is loaded, so the value can be inserted anywhere in the document. Disadvantage: won't work for clients that don't support or ignore Javascript.

  • Cheat and stop the timer early. You'll have to do all time-intensive stuff before the point in the document where you want the time (i.e. preload all results it in memory and echo it afterwards), so the part that you're not measuring is negligible. Disadvantage: it's not completely accurate and the pre-loading could be a hassle or memory-inefficient.

  • Buffer all output with output control functions and perform a search-and-replace on the output buffer contents at the end of the script. Disadvantage: could be inefficient depending on your situation.

Upvotes: 2

Chuck Harmston
Chuck Harmston

Reputation: 148

Not precisely, but you can get a very close approximation by using output buffering:

<?php

$time_start = microtime(true);

ob_start();
// Do stuff here
$page = ob_get_contents();
ob_end_clean();

$time_end = microtime(true);
$elapsed = number_format($time_end - $time_start, 5);

var_dump($page, $elapsed);

?>

Upvotes: 0

Related Questions