International PHP Conference Munich 2025

microtime

(PHP 4, PHP 5, PHP 7, PHP 8)

microtime 現在の Unix タイムスタンプをマイクロ秒まで返す

説明

microtime(bool $as_float = false): string|float

microtime() は、現在の Unix タイムスタンプをマイクロ秒単位で返します。 この関数は、gettimeofday() システムコールをサポートする オペレーティングシステムでのみ使用できます。

パフォーマンスの計測には、hrtime() を使うことをお勧めします。

パラメータ

as_float

true を指定すると、microtime() は文字列ではなく float を返すようになります。詳細は、戻り値の説明を参照ください。

戻り値

デフォルトでは、microtime() は "msec sec" 形式の文字列を返します。ただし、sec は Unix エポック (1970 年 1 月 1 日 0:00:00 GMT) からの経過秒数、msecsec から経過したマイクロ秒数を秒単位、つまり小数で表したものです。

as_floattrue に設定すると、microtime() は Unixエポック からの経過秒数を マイクロ秒で正確になるように float で表したものを返します。

例1 タイマスクリプト実行

<?php
$time_start
= microtime(true);

// しばらくスリープ
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo
"Did nothing in $time seconds\n";
?>

例2 microtime()REQUEST_TIME_FLOAT の例

<?php
// ランダムな時間のスリープ
usleep(mt_rand(100, 10000));

// REQUEST_TIME_FLOAT をスーパーグローバル $_SERVER から取得できます。
// ここにはリクエスト開始時のタイムスタンプがマイクロ秒の精度で記録されています。
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo
"Did nothing in $time seconds\n";
?>

参考

  • time() - 現在の Unix タイムスタンプを返す
  • hrtime() - システムの高精度な時刻を取得する

add a note

User Contributed Notes 2 notes

up
0
richardchen8426+php dot net at gmail dot com
1 day ago
The following tests execute with PHP 8.3.20

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$temp = 3 ** 1000;
}
$end = microtime(true);
echo "Exec time = " . ($end - $start) . " Second(s)" . PHP_EOL;
}

>> Exec time = 0.047096014022827 Second(s)

===

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$temp = pow(3, 1000);
}
$end = microtime(true);
echo "Exec time = " . ($end - $start) . " Second(s)" . PHP_EOL;
}

Exec time = 0.41157102584839 Second(s)
up
-1
mrnbknd at gmail dot com
10 days ago
Sometimes you need to get not seconds but milliseconds since the UNIX epoch:

function millis() : int {
[$milli, $seconds] = explode(' ', microtime()); // from string(21) "0.67932100 1748377570"
return intval($seconds) * 1000 // intval(0.67932100 * 1000) is 679
+ intval(doubleval($milli) * 1000); // 679 + (1748377570 * 1000) = full milliseconds (1000 ms per one s)
}
To Top