题
我注意到,无论给定脚本的执行时间如何,每个date()调用都将返回相同的时间戳,而不管脚本中调用函数的位置。看起来它只是返回脚本首次开始执行的时间。
为了进行日志记录,能够从脚本中获取增量时间戳非常有用。这可能吗?有没有办法做到相对轻量级?
编辑: microtime()功能的示例是否会显示它可能会这样做。任何人都可以确认吗?
更新: microtime()确实有效,但是我无法使用date()函数对其进行格式化,因为date()只接受时间戳作为整数(所以没有微秒)。如何从microtime()返回的值中获取格式正确的日期?
解决方案
http://us.php.net/microtime 在同一个剧本中给了我不同的时间
其他提示
首先, date()用于格式化时间戳 - 当没有第二个参数调用 date()
时,它只是默认行为,它将使用当前时间戳。使用的时间戳将是调用函数时的时间戳 - 调用 date('Ym-d')
与调用 date('Ym-d',time())相同
time()将为您提供 p>
[...]当前测量的时间 自Unix Epoch以来的秒数 (1970年1月1日00:00:00 GMT)。
每次调用 date()
时,您只会得到相同的时间戳,因为您的脚本太快并且在一秒钟内运行,导致没有时间戳更改。
解决格式化 microtime()的第二个问题返回值,您可以执行以下操作(未经测试)
function formatTime($microtime, $format)
{
list($timestamp, $fraction) = explode('.', $microtime);
return date($format, (int)$timestamp) . '.' . $fraction;
}
$ microtime
的值应为 float
,将 true
作为参数传递给 microtime时会得到()代码>
我在我的机器上运行了这段代码:
<?php
$time_start = time();
sleep(2);
$time_end = time();
print 'Start: ' . date("m/d/Y @ g:i:sA", $time_start) . '<br>';
print 'End: ' . date("m/d/Y @ g:i:sA", $time_end);
?>
输出:
Start: 10/23/2008 @ 3:12:23PM
End: 10/23/2008 @ 3:12:25PM
让我相信 time()
不会只返回执行开始的时间。
您可以使用 Pear Benchmarking package 获取时间和分析信息。