Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Initialise input
- define('TEST_SIZE', !isset($_GET['test_size']) || !is_numeric($_GET['test_size']) ? 10 : $_GET['test_size']);
- define('TYPE', !isset($_GET['type']) || !in_array($_GET['type'], array('array_walk', 'foreach')) ? 'array_walk' : $_GET['type']);
- define('TRUE_USAGE', isset($_GET['true_usage']));
- // Create form for test input
- ?>
- <form action="" method="get">
- <fieldset>
- <input type="checkbox" name="true_usage" <?php if (TRUE_USAGE) echo 'checked'; ?>>
- <label>True Memory Usage</label>
- </fieldset>
- <fieldset>
- <label>Test Size</label>
- <input name="test_size" type="text" value="<?php echo TEST_SIZE; ?>">
- </fieldset>
- <fieldset>
- <label>Type</label><br>
- <input name="type" type="radio" value="array_walk" <?php if (TYPE == 'array_walk') echo 'checked'; ?>>
- <label>array_walk</label><br>
- <input name="type" type="radio" value="foreach" <?php if (TYPE == 'foreach') echo 'checked'; ?>>
- <label>foreach</label>
- </fieldset>
- <button type="submit">Run</button>
- </form>
- <pre>
- Benchmark
- <?php
- // Create a class for testing
- class Test {
- private static $memory = null;
- private static $memory_peak = null;
- private static $time = null;
- public static function start() {
- self::$memory = memory_get_usage(TRUE_USAGE);
- self::$memory_peak = memory_get_peak_usage(TRUE_USAGE);
- self::$time = microtime(true);
- echo "Test started: ".TYPE.PHP_EOL;
- }
- public static function stop() {
- echo "Test stopped".PHP_EOL;
- echo "Memory: \t".number_format(memory_get_usage(TRUE_USAGE) - self::$memory).PHP_EOL;
- echo "Peak memory: \t".number_format(memory_get_peak_usage(TRUE_USAGE) - self::$memory_peak).PHP_EOL;
- echo "Time: \t\t".number_format(microtime(true) - self::$time, 6).PHP_EOL;
- }
- }
- // Initialise the data
- $recordset = array();
- for ($i = 0; $i++ < TEST_SIZE;) {
- $recordset[] = array('code' => $i, 'quantity' => rand(10, 30), 'amount' => rand(1, 5));
- }
- $total = array('quantity' => 0, 'amount' => 0, 'price' => null);
- // Run the test
- switch (TYPE) {
- case 'array_walk':
- Test::start();
- array_walk($recordset, function (&$value) use(&$total) {
- $value['price'] = ($value['amount'] == 0) ? null : $value['quantity'] / $value['amount'];
- $total['quantity'] += $value['quantity'];
- $total['amount'] += $value['amount'];
- });
- Test::stop();
- break;
- case 'foreach':
- Test::start();
- foreach ($recordset as $value) {
- $value['price'] = ($value['amount'] == 0) ? null : $value['quantity'] / $value['amount'];
- $total['quantity'] += $value['quantity'];
- $total['amount'] += $value['amount'];
- }
- Test::stop();
- break;
- }
- // Get the result
- $total['price'] = ($total['amount'] == 0) ? null : $total['quantity'] / $total['amount'];
- var_dump($total);
- ?>
- </pre>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement