How to calculate the elapsed time of an event

By Tony Marston

14th June 2003

Introduction
The code

Introduction

This tip is intended to show the novice PHP developer how to calculate the elapsed time for an event. This event may be the operation of a particular function, or it may be the operation of an entire script. No special modules are required as this script uses only standard PHP functions.

The code

The first step is to capture the start time for the event. The microtime() function provides two values - one in seconds and another in microseconds.

   list($usec, $sec) = explode(' ', microtime());
   $script_start = (float) $sec + (float) $usec;

When the event has completed you need similar code to capture the end time.

   list($usec, $sec) = explode(' ', microtime());
   $script_end = (float) $sec + (float) $usec;

The final step is to calculate the difference between the two times. Here I am rounding the result to 5 decimal places.

   $elapsed_time = round($script_end - $script_start, 5);

That is all there is to it.


© Tony Marston
14th June 2003

http://www.tonymarston.net
http://www.radicore.org

counter