Skip to content

Instantly share code, notes, and snippets.

@pix0r
Created September 25, 2015 13:50
Show Gist options
  • Select an option

  • Save pix0r/51cd8729b14ef80aef21 to your computer and use it in GitHub Desktop.

Select an option

Save pix0r/51cd8729b14ef80aef21 to your computer and use it in GitHub Desktop.

Revisions

  1. pix0r created this gist Sep 25, 2015.
    20 changes: 20 additions & 0 deletions output.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    $ php test.php
    Running 10 tests of 5000 iterations
    finished 1 of 10
    finished 2 of 10
    finished 3 of 10
    finished 4 of 10
    finished 5 of 10
    finished 6 of 10
    finished 7 of 10
    finished 8 of 10
    finished 9 of 10
    finished 10 of 10
    Function test_inline:
    Mean time: 1.1466787576675
    Min: 1.0665309429169
    Max: 1.2747008800507
    Function test_declared:
    Mean time: 1.1542639493942
    Min: 1.0916991233826
    Max: 1.2733070850372
    59 changes: 59 additions & 0 deletions test.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    <?php

    function get_long_array() {
    $arr = [];
    for ($x = 0; $x < 1000; $x++) {
    $arr[] = $x;
    }
    return $arr;
    }

    function test_inline($iterations) {
    for ($x = 0; $x < $iterations; $x++) {
    $sum = 0;
    foreach (get_long_array() as $k => $v) {
    $sum += $v;
    }
    }
    }

    function test_declared($iterations) {
    for ($x = 0; $x < $iterations; $x++) {
    $sum = 0;
    $result = get_long_array();
    foreach ($result as $k => $v) {
    $sum += $v;
    }
    }
    }

    $results = [
    'test_inline' => [],
    'test_declared' => [],
    ];

    $trials_per_func = 10;
    $iterations_per_test = 5000;

    echo "Running $trials_per_func tests of $iterations_per_test iterations\n";

    for ($x = 0; $x < $trials_per_func; $x++) {
    foreach (array_keys($results) as $funcname) {
    $time_start = microtime(true);
    $funcname($iterations_per_test);
    $time_end = microtime(true);
    $exec_time = $time_end - $time_start;
    $results[$funcname][] = $exec_time;
    }
    echo "finished " . ($x + 1) . " of $trials_per_func\n";
    }

    foreach ($results as $funcname => $func_results) {
    $mean = array_sum($func_results) / floatval(count($func_results));
    $max = max($func_results);
    $min = min($func_results);
    echo "Function $funcname:\n";
    echo "\tMean time: $mean\n";
    echo "\tMin: $min\n";
    echo "\tMax: $max\n";
    }