[eluser]Unknown[/eluser]
I often want to benchmark an activity that occurs many times during a single request.
Example
Code:
foreach ($files as $file) {
// S3: download profile file
$this->benchmark->mark("s3_download_start");
$this->s3->downloadFile($file);
$this->benchmark->mark("s3_download_end");
// PROFILE: import file to db
$this->benchmark->mark("profile_import_start");
$this->profile->import($file);
$this->benchmark->mark("profile_import_end");
}
I'd like the profiler to show me the total time for each of the two activities, but (as you probably know), it only reports the time elapsed between the last calls to each activity's start and end.
Proposed Solution
I've extended the core Benchmark class and overridden the mark and elapsed_time methods as follows:
Code:
function mark($name)
{
if (!array_key_exists($name, $this->marker)) $this->marker[$name] = array();
$this->marker[$name][] = microtime(true);
}
function elapsed_time($point1 = '', $point2 = '', $decimals = 4)
{
if ($point1 == '')
{
return '{elapsed_time}';
}
if ( ! isset($this->marker[$point1]))
{
return '';
}
if ( ! isset($this->marker[$point2]))
{
$this->marker[$point2] = array(microtime(true));
}
$iMSeconds = 0;
for ($iMark=0; $iMark<count($this->marker[$point1]); $iMark++){
$iMSeconds += $this->marker[$point2][$iMark] - $this->marker[$point1][$iMark];
}
return number_format($iMSeconds, $decimals);
}
Questions
Is this a good approach? Better ideas? Problems? Would this be useful for others?