1 <?php defined('SYSPATH') OR die('No direct access allowed.');
5 * $Id: Benchmark.php 4149 2009-04-01 13:32:50Z Shadowhand $
9 * @copyright (c) 2007 Kohana Team
10 * @license http://kohanaphp.com/license.html
12 final class Benchmark {
14 // Benchmark timestamps
15 private static $marks;
18 * Set a benchmark start point.
20 * @param string benchmark name
23 public static function start($name)
25 if ( ! isset(self::$marks[$name]))
27 self::$marks[$name] = array();
32 'start' => microtime(TRUE),
34 'memory_start' => self::memory_usage(),
35 'memory_stop' => FALSE
38 array_unshift(self::$marks[$name], $mark);
42 * Set a benchmark stop point.
44 * @param string benchmark name
47 public static function stop($name)
49 if (isset(self::$marks[$name]) AND self::$marks[$name][0]['stop'] === FALSE)
51 self::$marks[$name][0]['stop'] = microtime(TRUE);
52 self::$marks[$name][0]['memory_stop'] = self::memory_usage();
57 * Get the elapsed time between a start and stop.
59 * @param string benchmark name, TRUE for all
60 * @param integer number of decimal places to count to
63 public static function get($name, $decimals = 4)
68 $names = array_keys(self::$marks);
70 foreach ($names as $name)
72 // Get each mark recursively
73 $times[$name] = self::get($name, $decimals);
80 if ( ! isset(self::$marks[$name]))
83 if (self::$marks[$name][0]['stop'] === FALSE)
85 // Stop the benchmark to prevent mis-matched results
89 // Return a string version of the time between the start and stop points
90 // Properly reading a float requires using number_format or sprintf
92 for ($i = 0; $i < count(self::$marks[$name]); $i++)
94 $time += self::$marks[$name][$i]['stop'] - self::$marks[$name][$i]['start'];
95 $memory += self::$marks[$name][$i]['memory_stop'] - self::$marks[$name][$i]['memory_start'];
100 'time' => number_format($time, $decimals),
102 'count' => count(self::$marks[$name])
107 * Returns the current memory usage. This is only possible if the
108 * memory_get_usage function is supported in PHP.
112 private static function memory_usage()
118 // Test if memory usage can be seen
119 $func = function_exists('memory_get_usage');
122 return $func ? memory_get_usage() : 0;