PHP fstat()函数如何工作?

时间:2018-07-02 08:26:45

标签: php performance filesize 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);

2 个答案:

答案 0 :(得分:0)

我怀疑您在问,因为大小不符合您的预期。而且我怀疑它不是您期望的那样,因为在某些写操作仍处于缓冲状态时,您在关闭文件之前读取了大小

尝试先关闭文件,然后使用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>';

答案 1 :(得分:0)

经过一些测试,我认为函数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);
}