我在那裏,我正在編寫一個單元測試,聲明文件沒有被修改。測試代碼執行時間不到一秒,因此我想知道是否可以以毫秒爲單位檢索文件修改時間。 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