PHP execution time

PHP execution time

Last Updated on Feb 15, 2023


Sometimes it’s a good idea to calculate the execution time of your functions and script as a whole.

Especially for debugging slow scripts, if you calculate the execution time of each function you can analyze which function should be improved.

It’s very easy to do

  1. Before your function starts you store the microtime()
  2. Make sure you set true as the argument
  3. After the function ends you store the microtime again
  4. And then you have your execution time 

Let me show you an example:

function hello(){
     sleep(2); // wait for 2 seconds
     echo "hello world";

$start = microtime(true);
// hello world
$end = microtime(true);

$executionTime = $end - $start;
echo 'running the function took '. $executionTime;
// running the function took 2.0002160072327


Now you know about calculating the execution time of a script in PHP.

I recommend you to open a PHP files and write some functions. then try to calculate how long each one of them take to run.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • calculate execution time
  • microtime

Category: programming

Tags: #php #tips and tricks

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts