Tony Marston's Blog About software development, PHP and OOP

How to calculate the elapsed time of an event

Posted on 14th June 2003 by Tony Marston
Introduction
The code
Comments

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. Don't applaud, just throw money.


counter