Advertisement
Tuurlijk

Clean Int Array

Jan 17th, 2014
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 15.91 KB | None | 0 0
  1. <?php
  2. error_reporting(E_ALL & ~E_NOTICE);
  3. /*****************************************************************************
  4.  *  Copyright notice
  5.  *
  6.  *  ⓒ 2013 Michiel Roos <michiel@maxserv.nl>
  7.  *  All rights reserved
  8.  *
  9.  *  This script is part of the TYPO3 project. The TYPO3 project is free
  10.  *  software; you can redistribute it and/or modify it under the terms of the
  11.  *  GNU General Public License as published by the Free Software Foundation;
  12.  *  either version 2 of the License, or (at your option) any later version.
  13.  *
  14.  *  The GNU General Public License can be found at
  15.  *  http://www.gnu.org/copyleft/gpl.html.
  16.  *
  17.  *  This script is distributed in the hope that it will be useful, but
  18.  *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  19.  *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  20.  *  more details.
  21.  *
  22.  *  This copyright notice MUST APPEAR in all copies of the script!
  23.  ****************************************************************************/
  24.  
  25. // Setup
  26. $testName = 'Clean Integer Array';
  27. $reverseExecutionOrder = 0;
  28. $runs = 100;
  29.  
  30. // Parameter Sets
  31. $parameterSets = array(
  32.     'set1' => array (
  33.         'description' => 'Regular use',
  34.         'arr' => array('a', 'b', 1, 23 ,535 ,'d' , 'e', 'f')
  35.     )
  36. );
  37.  
  38. /*****************************************************************************
  39.  * Tests:
  40.  ****************************************************************************/
  41.  
  42. /**
  43.  * Baseline
  44.  */
  45. $descriptions['version1'] = 'Baseline';
  46. function version1($arr) {
  47.     foreach ($arr as $k => $v) {
  48.         $arr[$k] = intval($arr[$k]);
  49.     }
  50.     return $arr;
  51. }
  52.  
  53. $descriptions['version2'] = 'array_map';
  54. function version2($arr) {
  55.     return array_map('intval', $arr);
  56. }
  57.  
  58. $descriptions['version3'] = 'Lambda cast to int';
  59. $castToInt = function(&$v) {$v = (int)$v;};
  60. function version3($arr) {
  61.     global $castToInt;
  62.     return array_map($castToInt, $arr);
  63. }
  64.  
  65. $descriptions['version4'] = 'Lambda intval';
  66. $lambdaIntval = function(&$v) {$v = intval($v);};
  67. function version4($arr) {
  68.     global $lambdaIntval;
  69.     return array_map($lambdaIntval, $arr);
  70. }
  71.  
  72. $descriptions['version5'] = 'Closure cast to int';
  73. function version5($arr) {
  74.     array_walk($arr, function(&$n) {
  75.       $n = (int)$n;
  76.     });
  77. }
  78.  
  79. $descriptions['version6'] = 'Closure intval';
  80. function version6($arr) {
  81.     array_walk($arr, function(&$n) {
  82.       $n = intval($n);
  83.     });
  84. }
  85.  
  86.  
  87. /*****************************************************************************
  88.  * Helper functions needed for test:
  89.  ****************************************************************************/
  90.  
  91.  
  92. /*****************************************************************************
  93.  * System (look, but don't touch ;-) . . . only touch if you must.
  94.  ****************************************************************************/
  95.  
  96. // Show source?
  97. if (isset($_GET['source']) && $_GET['source']) {
  98.     show_source(__FILE__);
  99.     exit;
  100. }
  101.  
  102. // How many runs?
  103. if (isset($_GET['runs'])) $runs = preg_replace('/[^0-9]/', '', $_GET['runs']);
  104.  
  105. // Execution order?
  106. if (isset($_GET['reverseExecutionOrder'])) $reverseExecutionOrder = intval($_GET['reverseExecutionOrder']);
  107.  
  108. // Prepare
  109. $baselineTimes = $functionsToCall = $times = array();
  110. $allFunctions = get_defined_functions();
  111. $functions = array_filter($allFunctions['user'], create_function('$a','return strpos($a, "version") === 0;'));
  112. if ($reverseExecutionOrder) arsort($functions);
  113. foreach ($functions as $function) {
  114.     $xAxis[] = $function;
  115.     $functionsToCall[$function] = new ReflectionFunction($function);
  116. }
  117.  
  118. // Execute
  119. foreach ($parameterSets as $setName => $parameters) {
  120.     // Description is used later on, so clone the parameters
  121.     $functionParameters = $parameters;
  122.     unset($functionParameters['description']);
  123.     for ($i = 0; $i < $runs; $i++) {
  124.         foreach ($functions as $function) {
  125.             $start = microtime(TRUE);
  126.             $result = $functionsToCall[$function]->invokeArgs($functionParameters);
  127.             $time = microtime(TRUE) - $start;
  128.             if ($function === 'version1') {
  129.                 $baselineTimes[$setName] += $time * 1000;
  130.             }
  131.             if (is_array($result)) {
  132.                 $resultObjects[$setName][$function] = array_slice($result, 0, 20, TRUE);
  133.             } else {
  134.                 $resultObjects[$setName][$function] = $result;
  135.             }
  136.             $times[$setName][$function] += $time * 1000;
  137.         }
  138.     }
  139. }
  140.  
  141. function findWinner($times) {
  142.     $averagedTimes = array();
  143.     foreach ($times as $setName => $timeData) {
  144.         foreach ($timeData as $functionName => $time) {
  145.             $averagedTimes[$functionName] += $time;
  146.         }
  147.     }
  148.     asort($averagedTimes);
  149.     return $averagedTimes;
  150. }
  151.  
  152. $averagedTimes = findWinner($times);
  153.  
  154. /**
  155.  * Format an integer as a time value
  156.  *
  157.  * @param integer $time The value to format
  158.  *
  159.  * @return string
  160.  */
  161. function printSeconds($time) {
  162.     $prefix = '';
  163.     $suffix = 'μs';
  164.     if ($time < 0) {
  165.         $time = abs($time);
  166.         $prefix = '-';
  167.     }
  168.     if ($time === 0) {
  169.         $suffix = '';
  170.     }
  171.     if ($time >= 1000) {
  172.         $time = $time / 1000;
  173.         $suffix = 'ms';
  174.     }
  175.     if ($time >= 1000) {
  176.         $time = $time / 1000;
  177.         $suffix = ' s';
  178.     }
  179.     if ($time >= 60 && $suffix === ' s') {
  180.         $time = $time / 60;
  181.         $suffix = 'min!';
  182.     }
  183.     return $prefix . sprintf("%.2f {$suffix}", $time);
  184. }
  185.  
  186. ?>
  187. <html>
  188. <head>
  189.     <title><?php  echo $testName ?> | TYPO3 Tiny Test Suite</title>
  190.     <link rel="stylesheet" href="http://wiki.typo3.org/wiki/load.php?debug=false&amp;lang=en&amp;modules=mediawiki.legacy.commonPrint%2Cshared%7Cskins.typo3vector&amp;only=styles&amp;skin=typo3vector&amp;*" />
  191.     <script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
  192.     <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js" type="text/javascript"></script>
  193.     <script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script>
  194.     <script src="http://code.highcharts.com/modules/exporting.js" type="text/javascript"></script>
  195. </head>
  196. <body>
  197. <div id="content" class="mw-body">
  198.     <h1 id="top"><?php echo $testName ?></h1>
  199.     <form action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
  200.         <label for="runs">Run the tests how many times?</label>
  201.         <input name="runs" id="runs" value="<?php echo $runs ?>"/>
  202.         <label for="runs"><a href="#help">Reverse execution order?</a></label>
  203.         <input type="checkbox" name="reverseExecutionOrder" id="reverseExecutionOrder" value="1" <?php echo ($reverseExecutionOrder) ? 'checked="checked"' : '' ?>/>
  204.         <input class="submit" type="submit" value="Go!"/>
  205.     </form>
  206.     <p>Winner using averaged times over all sets: <strong><?php
  207.             $winner = array_slice($averagedTimes, 0, 1);
  208.             echo key($winner) ?></strong> <?php echo printSeconds(current($winner) / count($times)) ?>.</p>
  209.     <?php
  210.         if (count($parameterSets) > 1) {
  211.             echo '<ul>';
  212.             foreach ($averagedTimes as $function => $time) {
  213.                 echo '<li><b>' . $function . '</b>: ',
  214.                     ' ' . printSeconds($time / count($times)) . '</li>';
  215.             }
  216.             echo '</ul>';
  217.         }
  218.     ?>
  219.     <div id="resultGraph" style="min-width: 310px; min-height: 400px; margin: 0 auto"></div>
  220.     <?php
  221.         foreach ($times as $setName => $functionData) {
  222.             echo '<h2>' , ucfirst($setName) , '</h2>',
  223.                 '<p>' , $parameterSets[$setName]['description'] , '</p>',
  224.                 '<ul>';
  225.             foreach ($functionData as $function => $time) {
  226.                 $identifier = $setName . '-' . $function;
  227.                 echo '<li><a style="text-decoration: none" href="#', $identifier, '">',
  228.                     ucfirst($function),
  229.                     '</a> ',
  230.                     ': ',
  231.                     sprintf('<span style="min-width: 33px; display: inline-block; text-align: right; font-weight: bold;">%1.2d%%</span> ', $time * 100 / $baselineTimes[$setName]),
  232.                     sprintf('<span style="min-width: 50px; display: inline-block; text-align: right; margin: 0 10px;">%s</span> ', printSeconds($time)),
  233.                     $descriptions[$function],
  234.                     '</li>';
  235.             }
  236.             echo '</ul><h3>Parameters</h3><ul>';
  237.             foreach ($parameterSets[$setName] as $key => $value) {
  238.                 if ($key !== 'description') {
  239.                     if (is_array($value)) {
  240.                         echo '<li>' , $key , ':', '</li>'; var_dump($value);
  241.                     } else {
  242.                         echo '<li>' . $key . ' = "' . (string) $value . '"</li>';
  243.                     }
  244.                 } else {
  245.                     $setDescriptions[] = $value;
  246.                 }
  247.             }
  248.             echo '</ul>';
  249.         }
  250.     ?>
  251.     <script>
  252.         /**
  253.          * Format an integer as a time value
  254.          *
  255.          * @param {String} time The value to format in microseconds.
  256.          * @param {Number} decimals The amount of decimals
  257.          *
  258.          * @return string
  259.          */
  260.         function printSeconds(time, decimals) {
  261.            decimals = typeof decimals !== 'undefined' ? decimals : 2;
  262.             var prefix = '',
  263.                 suffix = 'μs';
  264.             if (time < 0) {
  265.                 time = Math.abs(time);
  266.                 prefix = '-';
  267.             }
  268.             if (time == 0) {
  269.                 suffix = '';
  270.             }
  271.             if (time >= 1000) {
  272.                 time = time / 1000;
  273.                 suffix = 'ms';
  274.             }
  275.             if (time >= 1000) {
  276.                 time = time / 1000;
  277.                 suffix = ' s';
  278.             }
  279.             if (time >= 60 && suffix == ' s') {
  280.                 time = time / 60;
  281.                 suffix = 'min!';
  282.             }
  283.             return prefix + Highcharts.numberFormat(time, decimals) + ' ' + suffix;
  284.         }
  285.  
  286.         var baseLineTimes = [<?php echo implode(',', $baselineTimes) ?>];
  287.         var descriptions = ['<?php echo implode("','", array_map('addslashes', $descriptions)) ?>'];
  288.         var setDescriptions = ['<?php echo implode("','", array_map('addslashes', $setDescriptions)) ?>'];
  289.         Highcharts.setOptions({
  290.             colors: ['#f58006', '#f50806', '#067bf5', '#f5bc06', '#8006f5']
  291.         });
  292.         jQuery(document).ready(function($) {
  293.             $('#resultGraph').highcharts({
  294.                 chart: {
  295. //                  type: 'bar'
  296.                     zoomType: 'y'
  297.                 },
  298.                 title: {
  299.                     text: '<?php echo $testName ?>'
  300.                 },
  301.                 xAxis: {
  302.                     categories: ['<?php echo implode("','", $xAxis)  ?>'],
  303.                     title: {
  304.                         text: null
  305.                     }
  306.                 },
  307.                 yAxis: {
  308.                     min: 0,
  309.                     title: {
  310.                         text: 'Time (milliseconds)',
  311.                         align: 'high'
  312.                     },
  313.                     labels: {
  314.                         overflow: 'justify',
  315.                         formatter: function() {
  316.                             return printSeconds(this.value);
  317.                         }
  318.                     }
  319.                 },
  320.                 tooltip: {
  321.                     useHTML: true,
  322.                     formatter: function() {
  323.                         return '<strong><a style="text-decoration: none" href="#' + this.point.series.name + '-' + this.point.category + '">' + descriptions[this.point.x] + '</a></strong><br/>' +
  324.                             setDescriptions[this.series.index] + '<br/>' +
  325.                             printSeconds(this.point.y) +
  326.                             ' (' + Math.ceil(this.point.y * 100 / baseLineTimes[this.point.series.index]) + '%)';
  327.                     }
  328.                 },
  329.                 legend: {
  330.                     enabled: true
  331.                 },
  332.                 credits: {
  333.                     enabled: false
  334.                 },
  335.                 series: [
  336.                     <?php
  337.                     foreach ($times as $setName => $setTimes) {
  338.                         $series[] = "{
  339.                             name: '" . $setName . "',
  340.                             data: [" . implode(',', $setTimes) . "]
  341.                         }";
  342.                     }
  343.                     echo implode(',', $series);
  344.                     ?>
  345.                 ]
  346.             });
  347.             $('#showSourceLink').on('click', function(e) {
  348.                 e.preventDefault();
  349.                 $.ajax({
  350.                     url: '<?php echo $_SERVER['SCRIPT_NAME'] ?>?source=1',
  351.                     cache: false
  352.                 })
  353.                 .done(function(html) {
  354.                     $('.loading').hide();
  355.                     $('#sourceCode').html(html);
  356.                     $('html, body').animate({
  357.                         scrollTop: $("#source").offset().top
  358.                     }, {
  359.                         duration: 2000,
  360.                         easing: 'easeOutBounce'
  361.                     });
  362.                 });
  363.             });
  364.             $('.top').on('click', function(e) {
  365.                 e.preventDefault();
  366.                 $('html, body').animate({
  367.                     scrollTop: $("#top").offset().top
  368.                 }, {
  369.                     duration: 2000,
  370.                     easing: 'easeOutBounce'
  371.                 });
  372.             });
  373.         });
  374.     </script>
  375.     <h2>Data results</h2>
  376.     <?php
  377.         foreach ($times as $setName => $functionData) {
  378.             echo '<h3>' . ucfirst($setName) . '</h3>';
  379.             echo '<p>' . $parameterSets[$setName]['description'] . '</p>';
  380.             echo '<ul>';
  381.             foreach ($parameterSets[$setName] as $key => $value) {
  382.                 if ($key !== 'description') {
  383.                     if (is_array($value)) {
  384.                         echo '<li>' , $key , ':', '</li>'; var_dump($value);
  385.                     } else {
  386.                         echo '<li>' . $key . ' = "' . (string) $value . '"</li>';
  387.                     }
  388.                 }
  389.             }
  390.             echo '</ul>';
  391.             foreach ($functionData as $function => $time) {
  392.                 echo '<h4 id="', $setName . '-' . $function, '">', ucfirst($function), '</h4>',
  393.                     '<p>', $descriptions[$function], '</p>';
  394.                 var_dump($resultObjects[$setName][$function]);
  395.                 echo '<a href="#top" class="top" style="color: #ddd; text-decoration: none;">^ top</a>';
  396.             }
  397.         }
  398.     ?>
  399.     <div id="p-personal" role="navigation" class="">
  400.         <ul>
  401.     <?php
  402.     foreach ($resultObjects as $setName => $functionData) {
  403.         foreach ($functionData as $function => $data) {
  404.             echo '<li><a href="#' . $setName . '-' . $function . '">' . ucfirst($setName) . ' ' . ucfirst($function)  . '</a></h3>';
  405.         }
  406.     }
  407.     ?>
  408.             <li><a href="#help">Help</a></li>
  409.             <li><a href="#source">Source Code</a></li>
  410.         </ul>
  411.     </div>
  412.     <div id="help">
  413.         <h2>Help</h2>
  414.         <h3>Execution Order</h3>
  415.         <p>In some cases, the second function (non baseline) always runs faster than the baseline. Even when switching the code around. This toggle enables you to reverse the running order to check for this behaviour. Your winning function should still win whatever the execution order. If that is not the case, then this test has failed to determine what code runs faster.</p>
  416.         <a href="#top" class="top" style="color: #ddd; text-decoration: none;">^ top</a>
  417.     </div>
  418.     <div id="source">
  419.         <h2>Source Code</h2>
  420.         <pre id="sourceCode"><a href="#source" id="showSourceLink">Show the sourcecode of this file.</a></pre>
  421.         <a href="#top" class="top" style="color: #ddd; text-decoration: none;">^ top</a>
  422.     </div>
  423.     <div id="logo" style="position: absolute; top: 60px; left: 60px;"><img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHYAAAAiCAYAAACKuC3wAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ
  424. bWFnZVJlYWR5ccllPAAABzJJREFUeNrsWwlsFUUYHh4VkEMEKaACHmAV0KTENFxaiIqK1sQDNYIS
  425. UTQRDSlH1DSIBqSgAQVijGIEjdYDREXEIEo4LSiKgFgUMKCAIK1KFQoUSv1++y/v7zCzZ1/bkP2T
  426. Lztv59jd+Wb+a/c1qKysVLGcftLAb8PKfNUQh8sYRxrkqUWGNpNweBhoI06XAiXALuBnoBBYgv77
  427. 4umvA2JBEtVlATcA13K5KVf3ADEbtPadcdju87rHgY+BURhnd0xDzUuagdAMHIYDg4HzDX3+1kll
  428. 6RjwuoOAnrje5Rjvn5iKFBGLCSYV+yxwu4eKtpFwIMT1aTHcCMyNqUgBsSB1NA75QGMffc6xnP89
  429. 1XY+Fv+SAKmP4DjNJ6kkzdGnwyns5Kn9OISxl3/FNKSAWODREP36Wc5/FWKsXTENqSG2W4h+11jO
  430. Lwo4zkFga0xDamxsGBt3PYVDUL96duMToBxo5HOc7zHGCUtda2B8iHtbAXzEjmBzseC+8Og3Asgw
  431. tD8TmAq04nCvMZ+juSsD9gLLOHzz40CeAdxGcwhczOORQ7qZnch1Ln3p+rdQuAlcAqQL/2Y58BZw
  432. 6H/TCIIogXBWiAnsC1IKDeHSh3zjfuQJjPG8pe5CYEeI+5oB5DIZY/jcFqA73Z6lTyfgFyarAqCY
  433. /FeuO5tCPJ++wgPAApc2GbwAurq0IXIeAo4a6jJpM7j03QYMoHtPhJw8kiEuE+tXFqZQG01j7aF4
  434. InNc2o4Wod/bglSTlPAEbgQ2iGuQhvkA6GXp14q1gCSVHM4iNkmO3AfM8vF8tNh+4gXpCO3i2Y6N
  435. LQo5cXdidzYyeMekCtf76L8Obbe41JOHfZEBss89hvoJXEcqco7UDi4qf7ijcIApHvedzjsvk1Ui
  436. JXFWC9M23dLvKdYMzuIgP6Uda5J07f6GAlcZxvhNVWUC2/J90yLpwmq9Qvg/3YjYNSGJTefskUny
  437. fPR/2aOe0o47DSgXbfYZ6mX4NFU8cF+GLhQVNOPyXN4FQaSEiXB8hZ7CVjtCdvRB8fsxtsuOHAHI
  438. JL2v3ZdJ3S8BirXzpAnmi9/ZROzKCOou15hxyFOf47DYpR+tvHdqwTmk3PU8l11LTtBI8XtKyOvs
  439. YLXsiK6Os4QfU8wq22uxXxfwHr4W5S5E7KYIWaMsqOM+Ll7mQUvdOJBfXkue/2RRztHCu2Eq+SZq
  440. oUZOUNmqOX5Semtee4VLHuAYl9uwmg2T6GmR4JAlihMzzrJrd7AjoIczi9lBqS3ZJOJrCu3GCns4
  441. VrTLj3gdObEttbpLRflHlzEqNFOQEeD6zUW5PMGFeREeaCB2bbaFXHLt71JV72QV3/RQQ/ybapGk
  442. 3csOzx3sbJF8CayNeI2GoqyHKvItmZd23CPKHQJcXy6e3Q6xyyOoY1fbBBLJqF/ANuNK/C6ug0RM
  443. ofAlKEEwSrO3k2rgGvLjgkNaXVvLzvba+e18XrsZL1RHViV48iu00CCo9MauHeJCbimwFCirwyzb
  444. ZM3p68HlNbywo0qmxd6SNBHlfz3GKdOyVCZpz3a8M4c65KyeK+x0YUI0ft0lM+NHpoPc9qr+ymKR
  445. tZFqc0INjN2PJ9mRtYYdZVPTusjdbssIvsee+HYmta/wjO92EhTS2VkQURUVgNy0ekzuZO33Bp6Y
  446. sELzR58NFYhzpPLr6o1Ve8cDT2gVL0QcmLIec/jDt/oo87XgfkYILXVAoJwdL8c5olBlTA3er+0F
  447. yUvsJxCeFjEs+TLvUkiXptnCVSBlhbK/b/Uj5HV2wjjjeeUexbh76gmxJzQbFuZznpaW8/Ss9BLg
  448. W0NdqZaF8nKEHLF9hqQnOCaqqjdrORzGjTCpzWe0dFcYyWaHhB6oqzq95E1RPqyqEvmFPGe2pIs8
  449. 38Jj/KaWfm5CWmemSr7o6J9m8GCXY7d9huJNNTAJuRhv72lG7P0h+vwhyq092sr6IN9e/yDKXRKW
  450. RhTjHY9qz0DqGyoWPSlxnkdbmcwIsimqqfuEJe6kt/kvRniQnSr5KiyW6mnC7i7tyOnMsPTzkiO6
  451. u24TsrXbQjwExWG3YnEciPk8Kd+I8tUu895LOFclKthHEDL9WJpwyRaVsYd7LKDXOQR9N8ZcVpPv
  452. hIdLacKBlnbDRHlpwGsMEOVtbjuWyKWVNjIAqZTgXxDzeIoc5vjSkekGW3uz5pjNNoxDb3CaGM53
  453. ZA17MkmS8LojEPUKDs95NDvGpBbEHFplooib6T0rpQPpw79XgVXApyqZ6qRs2BLDGIPY1FHflRzP
  454. Ejar5H+nyOl9zVf6D4Q9iRCojFeF/rkqfZs0mJIbMXeuQkka+l8UvcqkHDB9vWH6mnM9m0Cb0Gbs
  455. rKrnpqU8Tk5Xwu9dgThKllPKcDUHxOTC0+u6K2qZVPqP7UbGwRD9i0T/Uh/tK0T7qL7DMvaKSRVv
  456. VcmUIanqNWz2+rDjZLPVs7jtfpVMh/6pqjJP/Z1o5j8BBgADhL1q2hRfzwAAAABJRU5ErkJggg==" /></div>
  457. </div>
  458. </body>
  459. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement