Last active
December 17, 2019 06:07
-
-
Save Maff-/c4429a15f5a2eb8890477d8a259dd2b8 to your computer and use it in GitHub Desktop.
PHP Large Array Sum Micro Benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| declare(strict_types=1); | |
| printf("Current PHP version: %s\n", phpversion()); | |
| $iterations = (int)($_SERVER['argv'][1] ?? 2000); | |
| printf("Bench iterations: %d\n", $iterations); | |
| $time = microtime(true); | |
| //$input = array_map('intval', str_split(str_repeat(trim(file_get_contents('input.txt')), 100))); | |
| $input = array_fill(0, 65000, 1); | |
| printf("Loading input took %0.3fs\n", microtime(true) - $time); | |
| printf("(repeated) input length: %d\n", count($input)); | |
| $time = microtime(true); | |
| $sum = 0; | |
| for($i=0; $i < $iterations; $i++) { | |
| $sum += array_sum($input); | |
| } | |
| printf("array_sum took %0.3fs\n", microtime(true) - $time); | |
| $time = microtime(true); | |
| $sum = 0; | |
| for($i=0; $i < $iterations; $i++) { | |
| foreach($input as $digit) { | |
| $sum += $digit; | |
| } | |
| } | |
| printf("foreach +digit took %0.3fs\n", microtime(true) - $time); | |
| $rangeMin = $rangeLength = 16250; // 1/4 of input length | |
| $rangeMax = $rangeMin + $rangeLength; | |
| $time = microtime(true); | |
| $sum = 0; | |
| for($i=0; $i < $iterations; $i++) { | |
| $sum += array_sum(array_slice($input, $rangeMin, $rangeLength)); | |
| } | |
| printf("array_sum+array_slice took %0.3fs\n", microtime(true) - $time); | |
| $time = microtime(true); | |
| $sum = 0; | |
| for($i=0; $i < $iterations; $i++) { | |
| for ($j=$rangeMin; $j < $rangeMax; $j++){ | |
| $sum += $digit; | |
| } | |
| } | |
| printf("for +digit took %0.3fs\n", microtime(true) - $time); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $php bench.php 5000 | |
| Current PHP version: 7.4.0 | |
| Bench iterations: 5000 | |
| Loading input took 0.007s | |
| (repeated) input length: 65000 | |
| array_sum took 3.230s | |
| foreach +digit took 9.022s | |
| array_sum+array_slice took 1.245s | |
| for +digit took 2.729s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment