Skip to content

Instantly share code, notes, and snippets.

@f3ath
Created July 11, 2017 17:37
Show Gist options
  • Save f3ath/a799126a841ea5e614bb9f656613497e to your computer and use it in GitHub Desktop.
Save f3ath/a799126a841ea5e614bb9f656613497e to your computer and use it in GitHub Desktop.
<?php
echo "preparing test data file\n";
if (!file_exists('tmp')) {
$s = '';
for ($i = 0; $i < 1000000; $i++) {
$s .= rand() . 'asd';
}
file_put_contents('tmp', $s);
echo "file generated\n";
} else
echo "file already exists\n";
echo "test data prepared\n";
function bstr2bin($input)
{
if (!is_string($input)) {
return null;
}
$value = unpack('H*', $input);
return base_convert($value[1], 16, 2);
}
$s = file_get_contents('tmp');
$s_len = strlen($s);
echo "test 1 start\n";
$t1 = microtime(true);
$calc = 0;
for ($i = 0; $i < $s_len; $i += 2) {
$calc += array_sum(str_split(bstr2bin(substr($s, $i, 2))));
}
var_dump($calc, round((microtime(true) - $t1), 5) . 's');
var_dump($calc);
echo "test 2 start\n";
$t1 = microtime(true);
$calc = 0;
$map = [];
for ($i = 0; $i < $s_len; $i += 1024) {
foreach (str_split(substr($s, $i, 1024)) as $cur) {
if (@$map[$cur])
$map[$cur] = $map[$cur] + 1;
else
$map[$cur] = 1;
}
}
foreach ($map as $cur => $val) {
$calc += array_sum(str_split(bstr2bin((string)$cur))) * $val;
}
var_dump($calc, round((microtime(true) - $t1), 5) . 's');
var_dump($calc);
echo "test 3 start\n";
$t1 = microtime(true);
$calc = 0;
foreach (count_chars($s, 1) as $cur => $val) {
$calc += array_sum(str_split(bstr2bin(chr($cur)))) * $val;
}
var_dump($calc, round((microtime(true) - $t1), 5) . 's');
var_dump($calc);
echo "test 4 start\n";
$calc = 0;
$t1 = microtime(true);
foreach (count_chars($s, 1) as $i => $v) {
$calc += (($i & 1) + (($i >> 1) & 1) + (($i >> 2) & 1) + (($i >> 3) & 1) + (($i >> 4) & 1) + (($i >> 5) & 1) + (($i >> 6) & 1) + (($i >> 7) & 1)) * $v;
}
var_dump($calc, round((microtime(true) - $t1), 5) . 's');
var_dump($calc);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment