文件修改时间检查的成本 [英] Cost of file modification time checks

查看:55
本文介绍了文件修改时间检查的成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Linux下包含几个字节的文件,我只需要处理它自上次处理以来的更改时间.我通过调用 PHP clearstatcache(); 检查文件是否被更改;filemtime(); 定期.由于整个文件总是很小,删除对 filemtime 的调用并通过将内容与过去的内容进行比较来检查文件更改是否会提高性能?或者,就性能而言,最好的方法是什么.

For a file containing few bytes under Linux, I need only to process when it was changed since the last time it was processed. I check whether the file was changed by calling PHP clearstatcache(); filemtime(); periodically. Since the entire file will always be tiny, would it be a performance improvement to remove the call to filemtime and check for a file change by comparing the contents with the past contents? Or what is the best method for that, in terms of performance.

推荐答案

使用 filemtime + clearstatcache

Use filemtime + clearstatcache

为了增强@Ben_D 的测试:

To enhance @Ben_D's test:

<?php

$file = 'small_file.html';
$loops = 1000000;

// filesize (fast)
$start_time = microtime(1);
for ($i = 0; $i < $loops; $i++) {
    $file_size = filesize($file);
}
$end_time = microtime(1);
$time_for_file_size = $end_time - $start_time;

// filemtime (fastest)
$start_time = microtime(1);
for ($i = 0; $i < $loops; $i++) {
    $file_mtime = filemtime($file);
}
$end_time = microtime(1);
$time_for_filemtime = $end_time - $start_time;

// filemtime + no cache (fast and reliable)
$start_time = microtime(1);
for ($i = 0; $i < $loops; $i++) {
    clearstatcache();
    $file_mtime_nc = filemtime($file);
}
$end_time = microtime(1);
$time_for_filemtime_nc = $end_time - $start_time;

// file_get_contents  (slow and reliable)
$start_time = microtime(1);
for ($i = 0; $i < $loops; $i++) {
    $file_contents = file_get_contents($file);
}
$end_time = microtime(1);
$time_for_file_get_contents = $end_time - $start_time;

// output
echo "
<p>Working on file '$file'</p>
<p>Size: $file_size B</p>
<p>last modified timestamp: $file_mtime</p>
<p>file contents: $file_contents</p>

<h1>Profile</h1>
<p>filesize: $time_for_file_size</p>
<p>filemtime: $time_for_filemtime</p>
<p>filemtime + no cache: $time_for_filemtime_nc</p>
<p>file_get_contents: $time_for_file_get_contents</p>";

/* End of file */

这篇关于文件修改时间检查的成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆