php ファイルの作成が可能な「touch」と「file_put_contents」のパフォーマンスを計測する

php ファイルの作成が可能な「touch」と「file_put_contents」のパフォーマンスを計測する

phpで、ファイルの作成が可能な「touch」と「file_put_contents」のパフォーマンスを計測するサンプルコードを記述してます。phpのバージョンは8.0です。

環境

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

実行時間計測

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

$startTime = microtime(true);

// 処理を記述

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

以下は、「touch」と「file_put_contents」を使用して、ファイルを作成した後に、一度削除を行って、再度ファイルを作成するコードを10万回実行して、パフォーマンスを計測するサンプルコードとなります。

<?php

// 10万回実行
define('COUNT', 100000);

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

for ($i = 0; $i < COUNT; ++$i) {
    touch('hoge.txt');
    unlink('hoge.txt');
}

result($startTime, 'touch');

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

for ($i = 0; $i < COUNT; ++$i) {
    file_put_contents('hoge.txt','');
    unlink('hoge.txt');
}

result($startTime, 'file_put_contents');

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

実行結果

[1回目] 
測定結果 : touch
process time: 2.36517 ミリ秒

測定結果 : file_put_contents
process time: 2.92671 ミリ秒

[2回目] 
測定結果 : touch
process time: 2.40782 ミリ秒

測定結果 : file_put_contents
process time: 3.06328 ミリ秒

[3回目] 
測定結果 : touch
process time: 2.33405 ミリ秒

測定結果 : file_put_contents
process time: 2.92754 ミリ秒

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