Home > php > Measure execution time in PHP

Measure execution time in PHP

Problem

You want to measure the execution time of a piece of code.

Method #1

$start = (float) array_sum(explode(' ',microtime())); 
#	
// PHP code whose execution time you want to measure
#
$end = (float) array_sum(explode(' ',microtime()));
print "Processing time: ". sprintf("%.4f", ($end-$start))." seconds."; 

I found this tip here.

Method #2 (update 20110205)

There is a simpler solution; you can also write $start = microtime(true). See the PHP documentation here.

I use this method for simple profiling. For this, I use a class:

class Common
{
   /**
    * Get current microtime as a float. Can be used for simple profiling.
    */
   static public function get_microtime() {
      return microtime(true);
   }

   /**
    * Return a string with the elapsed time.
    * Order of $end and $start can be switched.
    */
   static public function elapsed_time($end, $start) {
      return sprintf("Elapsed time: %.4f sec.", abs($end - $start));
   }
}

Usage example:

$profile_start = Common::get_microtime();
// code to be profiled comes here
$profile_end = Common::get_microtime();
print Common::elapsed_time($profile_end, $profile_start);
Advertisements
Categories: php Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: