PHP Microtime Function

on Monday, 09 May 2011.

The PHP microtime() function returns the current Unix timestamp in microseconds.

microtime() returns a string and alternatively microtime(true) returns a float.

Usage

// microtime()
echo "microtime() = " . microtime() . " " 
  . ((is_string(microtime())) ? "string" : " not string") . "<br />"; 

// microtime(false)
echo "microtime(false) = " . microtime(false) . " " 
  . ((is_string(microtime(false))) ? "string" : " not string")  . "<br />"; 

// microtime(true)
echo "microtime(true) = " . microtime(true) . " " 
  . ((is_float(microtime(true))) ? "float" : " not float") . "<br />"; 

/* Sample Output
 
  microtime() = 0.49883700 1339648679 string
  microtime(false) = 0.49885600 1339648679 string
  microtime(true) = 1339648679.4989 float

 */

Helpful Examples

// Test your servers PHP execution time

// Start timer
$time_start = microtime(true);


// Code to test (the counter is an example)
$counter = 1;

while ($counter <= 1000000) {
  $counter++;
}


// End timer
$time_end = microtime(true);
$time = $time_end - $time_start;

echo "php execution time in microseconds: " . $time;

/* Sample Output
 
  php execution time in microseconds: 0.19492197036743

 */ 

Take it Further

You could extend this and set a maximum execution time variable. Then in the 'end timer' block check to see if it is exceeded and log or email the warning. This would be handy in determining server side performance issues.

Reference

microtime()

blog comments powered by Disqus