PHP records code running time, code running time measurement
Generally, the test code is added to the code that requires performance for calculation.
However, every time you write microtime, end-start may not be too troublesome, so you simply write a class.
Code
class TimeCost{ private $cost = array(); private $record = array(); private $scale = 6; public function __construct($scale = 6) { $this->cost = array(); $this->record = array(); $this->scale = $scale; } public function __toString() { return $this->getString(); } /** * start to cal time. * * @param mixed $key */ public function addCost($key) { $this->cost[$key] = microtime(true); } /** * stop to cal time. * * @param mixed $key */ public function closeCost($key) { $cost = bcsub(microtime(true), $this->cost[$key], $this->scale); if (in_array($key, array_keys($this->record))) { $this->record[$key] = bcadd($cost, $this->record[$key], $this->scale); } else { $this->record[$key] = $cost; } return $cost; } public function getString($key = null) { if ($key) { return "{$key}[{$this->record[$key]}]"; } $str = ''; foreach ($this->record as $k => $v) { $str .= "{$k}[{$v}]"; } return $str; }}
Usage
$obj = new TimeCost();$token = 'test_a';$obj->addCost($token);some_code();$obj->closeCost($token);$reslut = $obj->getString($token);
Description
-
Time precision: the default value is 6 bits, which is enough. to achieve higher precision, you can specify the $ scale parameter when creating a new object.
-
Token: token is used to indicate a piece of code. the corresponding result is written into the record array in the form of key (token) and value.
Therefore, the results of addCost and closeClost are accumulated multiple times with a token.
-
GetString: if the token is passed, the result corresponding to the token is returned. by default, all results in the record are spliced and returned.