編碼的世界 / 優質文選 / 文明

PHP獲取毫秒和微秒


2021年11月30日
-   

PHP獲取毫秒和微秒
這幾個概念的換算關系是:
1秒(second) = 1000毫秒(millisecond) = 1000,000微秒(microsecond)

PHP的microtime()函數可以獲取到微秒和毫秒數,但是和time() 函數不同,獲取到的不是int類型,而是字符串,也可以設置get_as_float 參數為true 返回浮點數(單位為秒)
返回字符串
官方文檔給的例子:
<?php
/**
* Simple function to replicate PHP 5 behaviour
*/
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
// Sleep for a while
usleep(100); //暫停100微秒
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "Did nothing in $time seconds
";
//輸出為
//Did nothing in 0.00037193298339844 seconds
//大概用了371微秒
?>

返回浮點數
這是PHP5開始有的特性
$start = microtime(true);
echo $start."
";
usleep(300);
$end = microtime(true);
echo $end;
/*
輸出為
1516631226.7536
1516631226.7559
單位為秒
*/

熱門文章