Last active
August 29, 2018 12:01
-
-
Save ihipop/14a148ebf48350fa8618cccc814a4837 to your computer and use it in GitHub Desktop.
测试 php 的 hash_map / 纯数组 查找元素速度和资源占用情况
This file contains 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 | |
function create_uuid() | |
{ | |
$str = md5(uniqid(mt_rand(), true)); | |
$uuid = substr($str, 0, 8) . '-'; | |
$uuid .= substr($str, 8, 4) . '-'; | |
$uuid .= substr($str, 12, 4) . '-'; | |
$uuid .= substr($str, 16, 4) . '-'; | |
$uuid .= substr($str, 20, 12); | |
return $uuid; | |
} | |
function getNiceFileSize($bytes, $binaryPrefix = true) | |
{ | |
if ($binaryPrefix) { | |
$unit = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; | |
if ($bytes == 0) { | |
return '0 ' . $unit[0]; | |
} | |
return @round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), 2) . ' ' . (isset($unit[$i]) ? $unit[$i] : 'B'); | |
} else { | |
$unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; | |
if ($bytes == 0) { | |
return '0 ' . $unit[0]; | |
} | |
return @round($bytes / pow(1000, ($i = floor(log($bytes, 1000)))), 2) . ' ' . (isset($unit[$i]) ? $unit[$i] : 'B'); | |
} | |
} | |
@$mode = $argv[1]; | |
$validMode = ['array', 'hash_map', 'isset_hash_map']; | |
if (!in_array($mode, $validMode)) { | |
echo 'Mode must :' . implode('|', $validMode) . PHP_EOL; | |
exit(1); | |
} | |
$max = 500 * 10000;//500万种子 | |
$needleIndex = random_int(1, $max);//保证这个种子在数组内的位置是随机的 | |
$needle = create_uuid();//用来检查的种子 | |
$array = []; | |
echo 'Current:' . getNiceFileSize(memory_get_usage(true)) . PHP_EOL; | |
$start = microtime(true); | |
for ($i = 1; $i <= $max; $i++) { | |
if ($i === $needleIndex) { | |
$uuid = $needle; | |
} else { | |
$uuid = create_uuid(); | |
} | |
if ($mode == 'array') { | |
$array[] = $uuid; | |
} else { | |
$array[$uuid] = $uuid; | |
} | |
} | |
$end = microtime(true); | |
echo 'Create Time: ' . sprintf('%0.15f', $end - $start) . PHP_EOL; | |
echo 'Total: ' . count($array) . PHP_EOL; | |
$searchTimes = 1000;//循环查找次数 | |
$start = microtime(true); | |
for ($i = 1; $i <= $searchTimes; $i++) { | |
if ($mode == 'array') { | |
in_array($needle, $array); | |
} elseif ($mode == 'hash_map') { | |
$array[$uuid]; | |
} else { | |
isset($array[$needle]); | |
} | |
} | |
$end = microtime(true); | |
echo 'Time for ' . $searchTimes . ' search: ' . sprintf('%0.15f', $end - $start) . PHP_EOL; | |
echo 'Peak:' . getNiceFileSize(memory_get_peak_usage(true)) . PHP_EOL; | |
echo 'Current:' . getNiceFileSize(memory_get_usage(true)) . PHP_EOL; |
Author
ihipop
commented
Aug 29, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment