PHP script execution time

I know there are many tutorials how to do this in PHP, but reason why I am writing this mini tutorial is one trick witch should help you a lot.

To calculate PHP script execution time is quite simple you just need to add below code to the top of your script code:

$time_start = microtime(true);

And at the end of string just add this:

$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Script took $time seconds\n";

And then you run this script you should get PHP script execution time at the bottom you should see how long script was running to generate page.

This works fine for simple pages, but what to do if you need to measure AJAX call, witch responds JSON data, script generation time? If you put this code in file where AJAX request is handled your JavaScript would get invalid JSON data because there should be string at the end of it.

To solve this problem is really simple all you have to do is to put script execution time to request headers:

header('ExTime: '.$time);

Just remember header() function should be called before any output. If you have output before you can modify your code something like this:

$time_start = microtime(true);

//... our script

$time_end = microtime(true);
$time = $time_end - $time_start;
header('ExTime: '.$time)
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *