3でも5でも割り切れる数の判定は
$num % 3 === 0 && $num % 5 === 0
より
$num % 15 === 0
の方が早いことの確認
何度か試したがおおむね100000ナノ秒だから0.1ミリ秒早いことが分かった。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
<?php function p($a = ''): void { echo $a . PHP_EOL; } function createRandomNums(int $length = 10000): array { for ($i = 0; $i < $length; $i++) { $nums[] = rand(); } return $nums; } function countMultiplesOf15(array $nums, callable $isMultiplesOf15): int { $cnt = 0; foreach ($nums as $num) { if ($isMultiplesOf15($num)) { $cnt++; } } return $cnt; } function calcTimeLapseNanoSec(array $start, array $end): int { $diffSec = $end[0] - $start[0]; $diffNanoSec = $end[1] - $start[1]; if (0 === $diffSec) { /* 秒の差がない */ return $diffNanoSec; } else { /* 秒の差がある */ return 1000000000 * $diffSec + $diffNanoSec; } } /** * 引数に渡した関数の処理時間(ナノ秒)を返却する */ function calcTimeLapseNanoSecForCallback(callable $callback): array { $start = hrtime(); $result = $callback(); $end = hrtime(); $timeLapseNanoSec = calcTimeLapseNanoSec($start, $end); return [ 'result' => $result, 'timeLapseNanoSec' => $timeLapseNanoSec, ]; } $isMultiplesOf15Double = function (int $num): bool { return ($num % 3 === 0 && $num % 5 === 0); }; $isMultiplesOf15Single = function (int $num): bool { return ($num % 15 === 0); }; $nums = createRandomNums(); $resultSingle = calcTimeLapseNanoSecForCallback( function () use ($nums, $isMultiplesOf15Single) { return countMultiplesOf15($nums, $isMultiplesOf15Single); } ); $resultDouble = calcTimeLapseNanoSecForCallback( function () use ($nums, $isMultiplesOf15Double) { return countMultiplesOf15($nums, $isMultiplesOf15Double); } ); p('$num % 3 === 0 && $num % 5 === 0'); print_r($resultDouble); p('$num % 15 === 0'); print_r($resultSingle); |
1 2 3 4 5 6 7 8 9 10 11 12 |
$num % 3 === 0 && $num % 5 === 0 Array ( [result] => 672 [timeLapseNanoSec] => 592282 ) $num % 15 === 0 Array ( [result] => 672 [timeLapseNanoSec] => 468077 ) |