Skip navigation

Measure script execution time in stages

We can use milestones in a script to track how certain sections of code are performing. The best way to achieve this is a simple function with some static variable inside. However, needs can quickly get complicated, so I built a simple static class to handle everything. Include this class in your application:

<?php
class ScriptTimer {
  static $milestones;
  function microtime_float() {
    list($utime, $time) = explode(" ", microtime());
    return ((float)$utime + (float)$time);
  }
  function timing_milestone($name) {
    self::$milestones[] = array($name, self::microtime_float());
  }
  function dump_profile($return = false) {
    self::$milestones[] = array('finish', self::microtime_float());
    $output = '<table border="1">'.
              '<tr><th>Milestone</th><th>Diff</th><th>Cumulative</th></tr>';
    foreach (self::$milestones as $elem => $data) {
      $output .= '<tr><td>'.$data[0].'</td>'.
        '<td>'.round(($elem ? $data[1] - self::$milestones[$elem - 1][1]: '0'), 5).'</td>'.
        '<td>'.round(($data[1] - self::$milestones[0][1]), 5).'</td></tr>';
    }
    $output .= '</table>';
    if ($return) return $output;
    echo $output;
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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: