jenwachter
10/3/2015 - 5:25 PM

A class to help benchmark php code.

A class to help benchmark php code.

<?php

$benchmarker = new Benchmarker($logger, "Main app");

// some code here

// add a benchmark
$benchmarker->log("After a bit of code");
<?php

class Benchmarker
{
  /**
   * Instance of logger adapter
   * https://github.com/johnshopkins/logger-exchange
   * @var object
   */
  protected $logger;

  /**
   * This benchmarker's label
   * @var string
   */
  protected $label;

  /**
   * Start time of the script
   * @var float
   */
  protected $start;
  
  public function __construct($logger, $label)
  {
    $this->logger = $logger;
    $this->label = $label;
    $this->start = microtime(true);
  }

  /**
   * Log a benchmark
   * @param  string $label Label of the benchmark
   * @return null
   */
  public function log($label)
  {
    $end = microtime(true);
    
    $this->logger->addInfo($label, array(
      "benchmarker" => $this->label,
      "time" => number_format($end - $this->start, 10)
      )
    );
  }
}