Do You PHP はてブロ

Do You PHPはてなからはてブロに移動しました

date.timezoneを設定するとdate()が早くなる

via. How much does a date() cost? – The Woodwork

らしいです。
php.iniの設定項目の1つであるdate.timezoneは、


環境変数 TZ が設定されていない場合、 全ての日付/時刻関数で使用されるデフォルトのタイムゾーン

というもので、PHP5.1.0から追加されてます。
設定しなくても動作するんですが、error_reportingにE_STRICTを追加すれば、タイムゾーンが設定されていない場合に次のようなStrictエラーが発生します。

Strict Standards: date(): It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Tokyo' for 'JST/9.0/no DST' instead in /path/to/script.php ...

このメッセージに書いてあるとおり、環境変数TZやphp.ini以外にもdate_default_timezone_set関数でも設定できます。

で、本題。
How much does a date() cost? – The Woodworkによると、タイムゾーン設定がされている場合とされていない場合でdate関数の実行速度が結構変わってくるようです。
ちょっと気になったので、

<?php
function microtime_float() {
    list($usec, $sec) = explode(' ', microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

for ($i = 0; $i < 100000; $i++) {
    date('YmdHis');
}

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "{$time} seconds\n";

というようなmicrotime関数のマニュアルにあるサンプルをちょこっと変えて、date関数を10万回実行する際の所要時間を見てみました。環境は

  • VMware on CF-R8
  • CentOS5.2
  • PHP5.2.8(src)

です。

$ for i in 1 2 3 4 5 6 7 8 9 10; do php -n date.php; done
4.9910509586334 seconds
4.7363398075104 seconds
4.9074039459229 seconds
5.0553238391876 seconds
5.4997420310974 seconds
5.1101479530334 seconds
4.8600640296936 seconds
5.2957248687744 seconds
4.7644650936127 seconds
4.8844192028046 seconds
$ for i in 1 2 3 4 5 6 7 8 9 10; do php -n -ddate.timezone='Asia/Tokyo' date.php; done
1.436096906662 seconds
1.4609639644623 seconds
1.3461771011353 seconds
1.4601330757141 seconds
1.3817000389099 seconds
1.4318227767944 seconds
1.2897689342499 seconds
1.455411195755 seconds
1.351322889328 seconds
1.3466069698334 seconds
$ 

VMware上のOSだと結構時間がずれたりするので微妙ですが、それなりの傾向は見て取れるかと。
ちなみに、ベンチマーク用のスクリプトも公開されていますので、そちらで試しても良いかも知れません。

タイムゾーンを考慮してるアプリだと少々面倒かも知れませんが、PHP.5.1.0以降を使っていてdate.timezoneを設定していない場合は設定しておいて損はないと思います(たぶん)。