<?php
/**
* Timestamp Performance Measurement with Manual Overrides
*/
class TimestampPerformance {
private $testName;
private $iterations;
private $startTimes = [];
private $endTimes = [];
private $results = [];
private $manualOverrideEnabled = false;
/**
* Constructor
* @param string $testName Name of the test
* @param int $iterations Number of iterations to run
*/
public function __construct(string $testName, int $iterations) {
$this->testName = $testName;
$this->iterations = $iterations;
}
/**
* Enable manual override mode. If enabled, timestamps are manually set.
* @param bool $enabled Whether to enable manual override.
*/
public function enableManualOverride(bool $enabled): void {
$this->manualOverrideEnabled = $enabled;
}
/**
* Record the start time for a test. Can be overridden manually.
* @param int $timestamp Timestamp to use as start. If manual override is enabled, this value is used.
* @return bool True on success, false on failure.
*/
public function start(int $timestamp = null): bool {
if ($this->manualOverrideEnabled) {
$this->startTimes[] = $timestamp;
return true;
} else {
$startTime = microtime(true);
$this->startTimes[] = $startTime;
return true;
}
}
/**
* Record the end time for a test. Can be overridden manually.
* @param int $timestamp Timestamp to use as end. If manual override is enabled, this value is used.
* @return bool True on success, false on failure.
*/
public function end(int $timestamp = null): bool {
if ($this->manualOverrideEnabled) {
$this->endTimes[] = $timestamp;
return true;
} else {
$endTime = microtime(true);
$this->endTimes[] = $endTime;
return true;
}
}
/**
* Perform the test and calculate performance.
* @return array An array of results.
*/
public function run(): array {
if (count($this->startTimes) !== count($this->endTimes)) {
error_log("Error: Number of start and end times do not match.");
return [];
}
$results = [];
for ($i = 0; $i < $this->iterations; $i++) {
$startTime = $this->startTimes[$i];
$endTime = $this->endTimes[$i];
$executionTime = $endTime - $startTime;
$results[] = [
'iteration' => $i + 1,
'execution_time' => $executionTime
];
}
return $results;
}
/**
* Get the results.
* @return array
*/
public function getResults(): array {
return $this->results;
}
}
/**
* Example Usage
*/
// Create a test object
$test = new TimestampPerformance('MyTest', 100);
// Enable manual override
$test->enableManualOverride(true);
// Simulate some work
for ($i = 0; $i < 1000; $i++) {
//Do something here
}
// Manually set start and end times for a specific iteration.
$test->start(time());
for ($i = 0; $i < 1000; $i++) {
//Do something here
}
$test->end(time() + 1);
// Run the test
$results = $test->run();
// Output the results
echo "<pre>";
print_r($results);
echo "</pre>";
//Example without manual override
$test2 = new TimestampPerformance('MyTest', 100);
$results2 = $test2->run();
echo "<pre>";
print_r($results2);
echo "</pre>";
?>
Add your comment