Skip to content

Instantly share code, notes, and snippets.

@doraemonxxx
Created June 30, 2022 20:58
Show Gist options
  • Select an option

  • Save doraemonxxx/d8a766703b37ff875872751aa7d8f83e to your computer and use it in GitHub Desktop.

Select an option

Save doraemonxxx/d8a766703b37ff875872751aa7d8f83e to your computer and use it in GitHub Desktop.
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
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment