php n乗計算を行う「gmp_pow」と「**」と「pow」のパフォーマンスを計測する

php n乗計算を行う「gmp_pow」と「**」と「pow」のパフォーマンスを計測する

phpで、n乗計算を行う「gmp_pow」と「**」と「pow」のパフォーマンスを計測するサンプルコードを記述してます。phpのバージョンは8.0です。

環境

  • OS  CentOS Stream release 8
  • php 8.0.0
  • nginx 1.14.1

実行時間計測

microtimeを使用すれば、処理にかかった時間を計測することが可能です。

$startTime = microtime(true);

// 処理を記述

$time = microtime(true) - $startTime; // 処理にかかった時間(ミリ秒)

以下は、「gmp_pow」と「**」と「pow」を使用して、2の5乗を計算するコードを1000万回実行して、パフォーマンスを計測するサンプルコードとなります。

<?php

// 1000万回実行
define('COUNT', 10000000);

// 計測開始
$startTime = microtime(true);

for ($i = 0; $i < COUNT; ++$i) {
    $result1 = gmp_pow(2, 5);
}

result($startTime, 'gmp_pow');

// 計測開始
$startTime = microtime(true);

for ($i = 0; $i < COUNT; ++$i) {
    $result2 = 2**5;
}

result($startTime, '**');

// 計測開始
$startTime = microtime(true);

for ($i = 0; $i < COUNT; ++$i) {
    $result3 = pow(2, 5);
}

result($startTime, 'pow');

function result($time, $str)
{
    echo '測定結果 : ' . $str . PHP_EOL;
    // 表示は少数第5桁まで
    echo "process time: " . number_format((microtime(true) - $time), 5) . ' ミリ秒' . PHP_EOL;
    echo PHP_EOL;
}

実行結果

[1回目] 
測定結果 : gmp_pow
process time: 5.41765 ミリ秒

測定結果 : **
process time: 0.69530 ミリ秒

測定結果 : pow
process time: 3.11623 ミリ秒

[2回目] 
測定結果 : gmp_pow
process time: 5.78756 ミリ秒

測定結果 : **
process time: 0.82867 ミリ秒

測定結果 : pow
process time: 2.97247 ミリ秒

[3回目] 
測定結果 : gmp_pow
process time: 4.95732 ミリ秒

測定結果 : **
process time: 0.69384 ミリ秒

測定結果 : pow
process time: 2.97423 ミリ秒

実行した結果を見る限り、「**」が圧倒的にパフォーマンスは良さそうです。