1<?php 2/* 3 * e107 website system 4 * 5 * Copyright (C) 2008-2010 e107 Inc (e107.org) 6 * Released under the terms and conditions of the 7 * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) 8 * 9 * Benchmark handler 10 * 11 * $URL$ 12 * $Id$ 13 */ 14 15 /** 16 * @package e107 17 * @subpackage e107_handlers 18 * @version $Id$ 19 * @author secretr 20 * 21 * Simple, quick and efective way of testing performance of parts of your code 22 * Example: 23 * <code> <?php 24 * require_once e_HANDLER.'benchmark.php'; 25 * 26 * $bench = new e_benchmark(); 27 * $bench->start(); 28 * 29 * // Do something, e.g. loop 1000000 times 30 * 31 * // stop timer and check your e_LOG folder 32 * $bench->end()->logResult('myevent'); 33 * //OR print out the result (don't forget to stop the timer if used without the above line! 34 * $bench->printResult(); 35 * </code> 36 */ 37class e_benchmark 38{ 39 protected $time_start; 40 protected $time_end; 41 42 /** 43 * Constructor 44 */ 45 function __construct() 46 { 47 $this->time_end = $this->time_start = 0; 48 } 49 50 /** 51 * Start timer 52 * @return benchmark 53 */ 54 public function start() 55 { 56 $this->time_start = microtime(true); 57 return $this; 58 } 59 60 /** 61 * Stop timer 62 * @return benchmark 63 */ 64 public function end() 65 { 66 $this->time_end = microtime(true); 67 return $this; 68 } 69 70 /** 71 * Calculate result 72 * @return integer 73 */ 74 public function result() 75 { 76 return ($this->time_end - $this->time_start); 77 } 78 79 /** 80 * Write result to a file in system log 81 * @param string $id identifier of the current benchmark event e.g. 'thumbnail.create' 82 * @param string $heading additional data to be shown in the log (header) e.g. '[Some Event]' 83 * @param boolean $append overwrite or append to the log file 84 * @return benchmark 85 */ 86 public function logResult($id, $heading = '', $append = true) 87 { 88 file_put_contents(e_LOG.'Benchmark_'.$id.'.log', $this->formatData($heading), ($append ? FILE_APPEND : 0)); 89 return $this; 90 } 91 92 /** 93 * Send result to the stdout 94 * 95 * @param string $heading 96 * @return string 97 */ 98 public function printResult($heading = '') 99 { 100 print('<pre>'.$this->formatData($heading).'</pre>'); 101 return $this; 102 } 103 104 /** 105 * Format data for loging/printing 106 * 107 * @param string $heading 108 * @return string 109 */ 110 function formatData($heading) 111 { 112 $data = "------------- Log Start -------------\n".date('r')." ".$heading."\n"; 113 $data .= "Result: ".$this->result()." sec\n------------- Log End -------------\n\n"; 114 return $data; 115 } 116}