Skip to content

Commit

Permalink
[Timer] New method stand-alone loopFunction()
Browse files Browse the repository at this point in the history
  • Loading branch information
jgauthi committed Jul 27, 2023
1 parent a272d17 commit 305e85f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
8 changes: 8 additions & 0 deletions example/timer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@
// In this example: 10 Loops, 100 executions by loop (total: 1000 executions)
$time->testLoop('filemtime', 10, 100, [__FILE__]);

// [Alternative] method stand-alone
$file = __FILE__;
var_dump(
'filemtime average time: '.
Timer::loopFunction(function() use ($file): void { filemtime($file); } )
);


// Define a location in the code to get the current time spent
$time->step('After testLoop');
sleep(1);
Expand Down
20 changes: 18 additions & 2 deletions src/Timer.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
/*******************************************************************************
* @name: Timer
* @note: Stopwatch in milliseconds script time+ the various steps in the code
* @author: Jgauthi <github.com/jgauthi>, created at [2mars2007]
* @version: 2.0
* @author: Jgauthi, created at [28mars2007], url: <https://github.com/jgauthi/component_debug>
* @version: 2.0.2
*******************************************************************************/

Expand Down Expand Up @@ -176,6 +176,22 @@ public function testLoop(callable $function, int $nb_loop = 10, int $nb = 100, a
return $this;
}

/**
* Method stand-alone
* Usage: \Jgauthi\Component\Timer::loopFunction(function() use ($var): void { somecode($var); } );
*/
public static function loopFunction(callable $closure, int $nbLoop = 100): float
{
$data = [];
for($i = 0; $i < $nbLoop; $i++) {
$time = microtime(true);
$closure();
$data[] = microtime(true) - $time;
}

return array_sum($data) / $nbLoop;
}

/**
* Exporte un chapitre au format CSV.
*/
Expand Down

0 comments on commit 305e85f

Please sign in to comment.