Print date time with ms in PHP, which is faster?

PHP 裡頭印出 Y-m-d h:i:s.u 的日期時間(有 ms)的方式很多,過年前無聊試了一下,還真的有些不一樣

想到的三種方式如下

  1. 用 DateTime::createFromFormat 並指定 format U.u (一般產生DateTime只會到 second)
  2. 用gettimeofday()拿['usec']
  3. 用microtime(true)並用字串處理的方式

分別 looping 1000*10 次

<?php
echo (microtime(true));
echo "<br>new DateTime with U.u then format<br>";
for ($i = 0; $i < 1000*10; $i++)
{
        $t = DateTime::createFromFormat("U.u",microtime(true));
        $t->format("Y-m-d H:i:s.u");
}

echo (microtime(true));
echo "<br><br>new DateTime, with gettimeofday()['usec']<br>";
for ($i = 0; $i < 1000*10; $i++)
{
        $t = (new DateTime())->format("Y-m-d H:i:s.") . gettimeofday()['usec'];
}

echo (microtime(true));
echo "<br><br>explode microtime, then date() and sprintf<br>";
for ($i = 0; $i < 1000*10; $i++)
{
        list($usec, $sec) = explode(" ", microtime());
        $milli = floor(((float) $usec) * 1000);
        $ts = date("Y M d H:i:s", (float) $sec) . "." . sprintf("%03d", $milli);

}

echo (microtime(true));
?>

結果如下:

1644158152.6933
new DateTime with U.u then format
1644158152.7722

new DateTime, with gettimeofday()['usec']
1644158152.9082

explode microtime, then date() and sprintf
1644158152.9817

結論是用 用microtime(true)並用字串處理的方式 的速度最快, DateTime::createFromFormat 小輸一點點