PHP microtime 返回当前 Unix 时间戳和微秒数
microtime
(PHP 4, PHP 5)
microtime — 返回当前 Unix 时间戳和微秒数
说明
mixed microtime ([ bool $get_as_float ] )
microtime() 当前 Unix 时间戳以及微秒数。本函数仅在支持 gettimeofday() 系统调用的操作系统下可用。
如果调用时不带可选参数,本函数以 "msec sec" 的格式返回一个字符串,其中 sec 是自 Unix 纪元(0:00:00 January 1, 1970 GMT)起到现在的秒数,msec 是微秒部分。字符串的两部分都是以秒为单位返回的。
如果给出了 get_as_float 参数并且其值等价于 TRUE,microtime() 将返回一个浮点数。
Note: get_as_float 参数是 PHP 5.0.0 新加的。
Example #1 用 microtime() 对脚本的运行计时
<?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);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "Did nothing in $time seconds ";
?>
PHP microtime note #1
I use this for measure duration of script execution. This function should be defined (and of couse first call made) as soon as possible.
<?php
/**
* get execution time in seconds at current point of call in seconds
* @return float Execution time at this point of call
*/
function get_execution_time()
{
static $microtime_start = null;
if($microtime_start === null)
{
$microtime_start = microtime(true);
return 0.0;
}
return microtime(true) - $microtime_start;
}
get_execution_time();