I've been dealing with a lot of long running scripts lately, so I started writing up a class to handle my benchmarking. Its not complete yet but you can see where I'm headed with it. Would you structure it any differently?
Code PHP:class benchmark { private $startTime; private $endTime; private $totalOps; private $opsCompleted; private $intervalOpsCompleted; private $benchInterval; //how far back in seconds the bench should look to calc private $lastBench; //time last bench was calculated private $benchResults; function __construct($totalOps) { $this->opsCompleted = 0; $this->intervalOpsCompleted = 0; $this->benchInterval = 60; $this->benchResults = array(); if($totalOps) { $this->totalOps = $totalOps; } } public function startBench() { if(!isset($this->startTime)) { $this->startTime = new DateTime("now"); $this->lastBench = new DateTime("now"); } else { throw new Exception("Bench has already been started in this object."); } } public function endBench() { if(!isset($this->endTime)) { $this->endTime = new DateTime("now"); } else { throw new Exception("Bench has already been ended in this object."); } } public function op() { $this->opsCompleted++; $this->intervalOpsCompleted++; //if dif between now and lastBench >= benchInterval, add benchmark $now = new DateTime("now"); $intervalDiff = $now->diff($this->lastBench); $intervalDiff = $intervalDiff->format('%s'); if($intervalDiff > $this->benchInterval) { $this->lastBench = new DateTime("now"); $this->intervalOpsCompleted = 0; array_push($this->benchResults, $this->getStatus()); } return $this->getStatus(); } public function getStatus() { $now = new DateTime("now"); //calculate overall ops per second $overallDiff = $now->diff($this->startTime); if($overallDiff->format('%s') == 0) { $overallOpsPerSecond = 0; } else { $overallOpsPerSecond = $this->opsCompleted / $overallDiff->format('%s'); } //calculate interval ops per second $intervalDiff = $now->diff($this->lastBench); if($intervalDiff->format('%s') == 0) { $intervalOpsPerSecond = 0; } else { $intervalOpsPerSecond = $this->opsCompleted / $intervalDiff->format('%s'); } return array( "startTime" => $this->startTime, "endTime" => $this->endTime, "elapsedTime" => $overallDiff, "opsCompleted" => $this->opsCompleted, "overallOpsPerSecond" => $overallOpsPerSecond, "benchInterval" => $this->benchInterval, "intervalOpsCompleted" => $this->intervalOpsCompleted, "intervallOpsPerSecond" => $intervalOpsPerSecond ); } }
EDIT: Whats the best way to handle optional arguments, often seen passed in arrays in the newer PHP classes. Currently I have an unused $totalOps arguement which spits out an ugly warning when not supplied.




Reply With Quote





Bookmarks