Skip to content

Instantly share code, notes, and snippets.

@ckdarby
Created November 20, 2013 22:22
Show Gist options
  • Save ckdarby/7572203 to your computer and use it in GitHub Desktop.
Save ckdarby/7572203 to your computer and use it in GitHub Desktop.
Monitoring File Changes in PHP
stat
avg: 0.216100677729
min: 0.167356967926
max: 0.367993116379
sha1_file
avg: 0.456373734236
min: 0.385113954544
max: 0.842865943909
filemtime
avg: 0.210854323149
min: 0.177852153778
max: 0.37334394455
<?php
/**
* Benchmarks the running time of the supplied closure and outputs its average,
* min and max over the given number of iterations.
*
* @param string $title Title of the benchmark to print
* @param int $iterations Number of times to run the anonymous function
* @param callable $callable The function to measure
*/
function benchmark($title, $iterations, $callable)
{
$runningTimes = [];
for ($i = 0; $i < $iterations; $i++) {
$startTime = microtime(true);
$callable();
$endTime = microtime(true);
$time = $endTime - $startTime;
$runningTimes[] = $time;
}
$avg = array_sum($runningTimes) / count($runningTimes);
$min = min($runningTimes);
$max = max($runningTimes);
echo "\n$title\navg: $avg\nmin: $min\nmax: $max\n";
}
/**
* If the given path is a file, the function is called with the path as its
* argument. Otherwise, if the path is a directory, this function recurses over
* all sub-folders, invoking the $callable for each file.
*
* @param string $path A valid path to a file or directory
* @param callable $callable The function to invoke for each file found, with
* its path as the argument
*/
function recurseCall($path, $callable)
{
if (is_file($path)) {
$callable($path);
return;
}
$path = realpath($path);
$dirIterator = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($dirIterator);
$files = new RegexIterator($iterator, '/^.+\.php$/i',
RecursiveRegexIterator::GET_MATCH);
foreach ($files as $file) {
$filePath = $file[0];
if (is_file($filePath)) {
$callable($filePath);
}
}
}
$directory = dirname(__FILE__) . '/Symfony';
// Using stat size and mtime
benchmark('stat', 1000, function() use ($directory) {
clearstatcache();
recurseCall($directory, function($path) {
$stat = stat($path);
// $stat['mtime'], $stat['size'];
});
});
// Using sha1_file
benchmark('sha1_file', 1000, function() use ($directory) {
recurseCall($directory, function($path) {
$digest = sha1_file($path);
});
});
// Using filemtime
benchmark('filemtime', 1000, function() use ($directory) {
recurseCall($directory, function($path) {
$time = filemtime($path);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment