Skip to content

Instantly share code, notes, and snippets.

@netebakari
Created January 8, 2021 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netebakari/88bc4db8a39180626d9b3023740daa2d to your computer and use it in GitHub Desktop.
Save netebakari/88bc4db8a39180626d9b3023740daa2d to your computer and use it in GitHub Desktop.
長い文字列を与えたときのmb_substr()の処理時間を調べる
<?php
/* 文字列を倍々に増やしていって指定された長さ以上の文字列を作る */
function generate_long_string($min_length_in_bytes) {
$str = "1234567890";
while(strlen($str) < $min_length_in_bytes) {
$str .= $str;
}
return $str;
}
/**
* 指定された文字列、指定された開始位置から1文字を切り出す処理を繰り返し、
* 1回あたりにかかった時間をミリ秒単位で返す
*/
function pick($str, $start, $repeat_count) {
$now1 = microtime(true);
$match = 0;
for($i = 0; $i <= $repeat_count; $i++) {
$s = mb_substr($str, $start, 1);
}
$now2 = microtime(true);
$duration = $now2 - $now1;
return $duration * 1000 / $repeat_count;
}
$str = generate_long_string(500*1000); //656KB
echo("STRING LENGTH=". strlen($str). "\n");
echo("\n");
// 0文字目, 1万文字目, 2万文字目, ...から1文字取るのにかかる時間を調べる
for ($i = 0; $i <= 50; $i++) {
$pos = $i * 10000;
$result = pick($str, $pos, 100);
echo($pos. ":". $result. "\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment