PHP获取毫秒和微秒及换算关系

作者:有用网 阅读量:412 发布时间:2022-10-12
关键字 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\n";
//输出为
//Did nothing in 0.00037193298339844 seconds
//大概用了371微秒
?>


返回浮点数

这是PHP5开始有的特性

$start = microtime(true);
echo $start."\n";
usleep(300);
$end = microtime(true);
echo $end;
/*
输出为
1516631226.7536
1516631226.7559
单位为秒
*/

#发表评论
提交评论