PHP fstat() 函数如何工作?



PHP fstat(( 函数如何工作?

该函数是否在每次调用时从磁盘读取文件大小?

还是该函数根据执行的所有写入操作计算大小?

例:

$filename='abc.txt';
$fp=fopen($filename, 'a');
$fstat=fstat($fp);
echo 'Size: '.$fstat['size'].'<br><br>';
echo 'Writing...<br><br>';
fwrite($fp, 'xx');
fwrite($fp, 'yyyy');
// ...
// Some number of fwrite() opertions
// ...
fwrite($fp, 'zzzzzz');
$fstat=fstat($fp);
echo 'Size after writing: '.$fstat['size'].'<br>';
// Does the size is read from disk or is calculated based on earlier writing operations?
fclose($fp);

我怀疑你在问,因为大小不像你预期的。我怀疑它不像您期望的那样,因为当某些写入仍在缓冲时,您在关闭文件之前读取了大小。

尝试关闭文件,然后使用stat()

$filename='abc.txt';
$fp=fopen($filename, 'a');
$fstat=fstat($fp);
fwrite($fp, 'xx');
fwrite($fp, 'yyyy');
...
...
fclose($fp);

$stat=stat($filename);
echo 'Size after writing: '.$stat['size'].'<br>';

经过一些测试,我认为函数 fstat(( 计算大小,因为它比带有 clearstatcache(( 的 filesize(( 快得多。

代码:

for (/*loop for 10 000 files*/) {
fwrite($fp, '123');
$fstat=fstat($fp);
fwrite($fp, '123');
$fstat=fstat($fp);
fwrite($fp, '123');
$fstat=fstat($fp);
}

类似于(性能(于:

// Here filesize() is BUFFERED and gives wrong results
for (/*loop for 10 000 files*/) {
fwrite($fp, '123');
$fsize=filesize($filename);
fwrite($fp, '123');
$fsize=filesize($filename);
fwrite($fp, '123');
$fsize=filesize($filename);
}

比以下速度快:

// Here filesize() reads size on every call
for (/*loop for 10 000 files*/) {
fwrite($fp, '123');
clearstatcache();
$fsize=filesize($filename);
fwrite($fp, '123');
clearstatcache();
$fsize=filesize($filename);
fwrite($fp, '123');
clearstatcache();
$fsize=filesize($filename);
}

并且比:

// Here filesize() reads size on every call
for (/*loop for 10 000 files*/) {
fwrite($fp, '123');
clearstatcache(true, $filename);
$fsize=filesize($filename);
fwrite($fp, '123');
clearstatcache(true, $filename);
$fsize=filesize($filename);
fwrite($fp, '123');
clearstatcache(true, $filename);
$fsize=filesize($filename);
}

相关内容

  • 没有找到相关文章

最新更新