Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save evert0n/6056176 to your computer and use it in GitHub Desktop.
Save evert0n/6056176 to your computer and use it in GitHub Desktop.
<?php
/*
* Benchmark counting file lines using `wc -l` vs `fopen and feof`
*
*/
$file = 'csv-file-1000000-rows.csv';
// Using `wc -l`
$time_start = microtime(true);
$lines = trim(shell_exec('wc -l '. $file));
$time_end = microtime(true);
$time = round($time_end - $time_start, 3);
echo 'Finished with '. $time .'s using `wc -l`. Result: '. $lines .PHP_EOL;
echo PHP_EOL;
// Using `fopen and feof`
$lines = 0;
$time_start = microtime(true);
$fp = fopen($file, 'r');
while (!feof($fp)) {
$line = fgets($fp);
$lines++;
}
fclose($fp);
$time_end = microtime(true);
$time = round($time_end - $time_start, 3);
echo 'Finished with '. $time .'s using `fopen and feof`. Result: '. $lines .PHP_EOL;
echo PHP_EOL;
// Finished with 2.311s using `wc -l`. Result: 1000001 csv-file-1000000-rows.csv
//
// Finished with 4.346s using `fopen and feof`. Result: 1000002
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment