Подтвердить что ты не робот

Стоимость проверки времени изменения файла

Для файла, содержащего несколько байтов в Linux, мне нужно только обрабатывать, когда он был изменен с момента последнего его обработки. Я проверяю, был ли файл изменен, вызывая PHP clearstatcache(); filemtime(); периодически. Поскольку весь файл всегда будет крошечным, было бы ли улучшение производительности удалять вызов filemtime и проверять изменение файла, сравнивая содержимое с прошлым содержимым? Или лучший способ для этого, с точки зрения производительности.

4b9b3361

Ответ 1

Используйте filemtime + clearstatcache

Чтобы усилить тест @Ben_D:

<?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 */

Results

Ответ 2

Я знаю, что опаздываю на вечеринку, но небольшой бенчмаркинг никогда не повредит дискуссиям. Интуиция Брайана Роуча доказывает звуки, даже если вы не примете во внимание шаг сравнения:

Тест:

$file = "small_file.html";
$file_size = filesize($file);

//get the filemtime 1,000,000 times
$start_time = microtime(true);
for($i=0;$i<1000000;$i++){
    $set_time = filemtime($file);
}
$end_time = microtime(true);

$time_for_filemtime = ($end_time-$start_time);

//get the time for file_get_contents 1,000,000 times
$start_time = microtime(true);
$file = "small_file.html";
for($i=0;$i<1000000;$i++){
    $set_time = file_get_contents($file);
}
$end_time = microtime(true);

$time_for_file_get_contents = ($end_time-$start_time);

echo "<p>Working on a file that is $file_size B long</p>
<p>filemtime: $time_for_filemtime vs file_get_contents: $time_for_file_get_contents";

Результаты

Работа с файлом длиной 41 B

filemtime: 0.36287999153137 vs file_get_contents: 16.191468000412

Отсутствие шока: "задание файловой системы для некоторых метаданных" происходит быстрее, чем "открытие файла, его чтение и сравнение содержимого".

Ответ 3

Чтобы скопировать файл, вы просто запрашиваете файловую систему для некоторых метаданных.

Ваш второй подход включает открытие файла, его чтение и сравнение содержимого.

Как вы думаете, будет быстрее?;)

Ответ 4

Я думаю, что лучший способ для уведомления об изменениях в файле - inotify, который предназначен именно для этой цели.

См. расширение inotify.