Simple performance testing for functions within Drupal

Type: 
Code
Date: 
February 5, 2010

I needed to quickly test some functions to see how much time and memory they were consuming. I wanted to quickly add a short function throughout each step in the function, have it record how much time had elapsed since start, also log how much memory was being consumed, and upon completion output a table of the results.

So, I wrote a short utility function called tp() to record time points and memory usage.

Here is the function:

function tp($description = '', $report = false) {
  static $time_point_start;
  static $time_point_last_split;
  static $time_point_results;
  
  // Initialize variables if starting up
  if(!$time_point_start) {
    $time_point_start = time();
    $time_point_last_split = time();
    $time_point_results = array();
    $time_point_results[] = array(' -- ', ' -- ', ' -- ', format_size(memory_get_usage(TRUE)));
    return;
  }
  
  // Collect data to record
  $split = date('i:s', time() - $time_point_last_split);
  $total = date('i:s', time() - $time_point_start);
  $time_point_memory = memory_get_usage();
  
  // Build table row
  $time_point_results[] = array($description, $split, $total, format_size(memory_get_usage(TRUE)));
  
  // Update for next round
  $time_point_last_split = time();
  
  // Output data to Drupal message if requested
  if($report) {
    $output = theme_table(array('Point', 'Split', 'Total', 'Memory'), $time_point_results);
    drupal_set_message($output);
  }
}

Here is an example of how it is used:

function script_to_test() {
  
  // This starts time point
  tp();
  
  $i = 0;
  while($i < 10000000) {
    ++$i;
  }
  
  // Adds entry
  tp('after first loop');
  
  $i = 0;
  while($i < 10000000) {
    ++$i;
  }
 
  // Adds entry and outputs report to Drupal
  tp('after last loop', TRUE);
}

Hope this is helpful.

Cheers, Jason