我在那里,我正在编写一个单元测试,声明文件没有被修改。测试代码执行时间不到一秒,因此我想知道是否可以以毫秒为单位检索文件修改时间。 filemtime()函数以秒为单位返回UNIX时间戳。PHP文件修改时间(以毫秒为单位)
我目前的解决方案是使用sleep(1)函数,它可以确保在检查它是否被修改之前通过了1秒。我不喜欢这个解决方案,因为它会大大减缓测试的速度。
我无法通过get_file_contents()声明内容相等,因为可以重写的数据是相同的。
我猜这是不可能的,是吗?
我在那里,我正在编写一个单元测试,声明文件没有被修改。测试代码执行时间不到一秒,因此我想知道是否可以以毫秒为单位检索文件修改时间。 filemtime()函数以秒为单位返回UNIX时间戳。PHP文件修改时间(以毫秒为单位)
我目前的解决方案是使用sleep(1)函数,它可以确保在检查它是否被修改之前通过了1秒。我不喜欢这个解决方案,因为它会大大减缓测试的速度。
我无法通过get_file_contents()声明内容相等,因为可以重写的数据是相同的。
我猜这是不可能的,是吗?
AFAIK UNIX时间戳的精度是秒,所以这可能不是一个可能性。
顺便说一下,请注意,PHP在内部缓存返回值filemtime()
,因此应在之前调用clearstatcache()
。
另一种方法可能是首先修改(或删除)文件的内容,以便您可以轻松识别更改。由于每次测试执行后系统的状态应该保持不变,因此无论如何在单元测试运行后恢复原始文件内容是有意义的。
试试这个简单的命令:
ls --full-time 'filename'
,你可以看到该文件的时间戳精度不第二,它是更精确。 (使用Linux,但不认为它在Unix中有所不同) 但我仍然不知道获取精确时间戳的PHP函数,也许你可以解析系统调用的结果。
如果文件系统是ext4
(在Ubuntu等更新的unixes/Linux中很常见)或ntfs
(Windows),那么mtime
确实具有亚秒级精度。
如果文件系统是ext3
(或许其他;这是标准,而且现在仍被RHEL使用),那么mtime
只存储到最近的秒钟。也许这种旧的默认值是为什么PHP只支持mtime
到最近的秒钟。
要在PHP中获取值,您需要调用外部util,因为PHP本身不支持它。
(我已经测试只有一个英语语言环境的系统上使用以下;的stat
的“人类可读”输出可以是不同的,或strtotime
行为可以在非英语语言环境不同应该在任何时区很好地工作。作为stat
输出包括由strtotime
兑现一个时区指定符)
class FileModTimeHelper
{
/**
* Returns the file mtime for the specified file, in the format returned by microtime()
*
* On file systems which do not support sub-second mtime precision (such as ext3), the value
* will be rounded to the nearest second.
*
* There must be a posix standard "stat" on your path (e.g. on unix or Windows with Cygwin)
*
* @param $filename string the name of the file
* @return string like microtime()
*/
public static function getFileModMicrotime($filename)
{
$stat = `stat --format=%y $filename`;
$patt = '/^(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d)\.(\d+) (.*)$/';
if (!preg_match($patt, $stat, $matches)) {
throw new \Exception("Unrecognised output from stat. Expecting something like '$patt', found: '$stat'");
}
$mtimeSeconds = strtotime("{$matches[1]} {$matches[3]}");
$mtimeMillis = $matches[2];
return "$mtimeSeconds.$mtimeMillis";
}
}
(通过使用例如''stat --format =“%Y%y”$ filename''来避免'strtotime'调用可能会更安全,但我现在已经写了这个版本。) – Rich 2013-09-30 17:49:57
function getTime($path){
clearstatcache($path);
$dateUnix = shell_exec('stat --format "%y" '.$path);
$date = explode(".", $dateUnix);
return filemtime($path).".".substr($date[1], 0, 8);
}
的getTime( “myTestTile”);
我喜欢这个想法,我更喜欢操纵内容而不是睡1秒,这样更快。谢谢你的提示。 – 2010-05-28 14:41:52