Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Bypass system cache option to Copy/Move dialog #756

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

check4game
Copy link

@check4game check4game commented Dec 4, 2023

Summary

Обход системного кэша при копировании/перемещении больших файлов между папками или между разными дисками

References

Checklist

  • I have followed the contributing guidelines.
  • I have discussed this with project maintainers:

    If not checked, I accept that this work might be rejected in favor of a different grand plan.

Details

Мне видится что будет полезным отключать системный кэш, для таких операций ( позволяет ускорить процесс по времени и исключить вытеснение пользовательских данных из системного кэша на файловых серверах)

Обход системного кэша, осуществляется через установку флага COPY_FILE_NO_BUFFERING при вызове функции CopyFileEx.

Дополнительно введен минимальный размер файла для которого данный флаг устанавливается

Заранее прошу извинить если что-то забыл указать по данному улучшению, я делаю это впервые.

Setup Bypass system cache  vi COPY_FILE_NO_BUFFERING flag for CopyFileEx windows api function only
Copy link

sonarcloud bot commented Dec 4, 2023

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 0 Code Smells

No Coverage information No Coverage information
No Duplication information No Duplication information

@alabuzhev
Copy link
Contributor

On general idea:

Sounds interesting, but do you just think it will be useful, or have you actually measured it and noticed a substantial difference?
What other known file managers, copy tools etc. implement this?

On implementation:

  1. We have 2 copy routines: a CopyFileEx call and a ReadFile + WriteFile loop.
    The current change only covers the CopyFileEx path.
    If we decide to add it, the other one must be covered too, supposedly using FILE_FLAG_NO_BUFFERING.

    • There are certain requirements when working without buffering. We will need to ensure that memory buffers and file reads and writes are properly aligned, including when dealing with sparse files.
  2. "Large file" is a relative concept.
    1 GB file is probably "large" for a system with 4 GB RAM, but probably "nothing" for a system with 64 GB RAM.
    I doubt that an average user can figure out on their own where to draw the line.
    I suspect that an average user will most likely set it incorrectly, making things worse.
    If we decide to add it, the limit should probably be calculated automatically (e.g. 10-20% of RAM) and applied automatically without exposing any knobs to the user.

@check4game
Copy link
Author

On general idea:

Sounds interesting, but do you just think it will be useful, or have you actually measured it and noticed a substantial difference? What other known file managers, copy tools etc. implement this?

On implementation:

  1. We have 2 copy routines: a CopyFileEx call and a ReadFile + WriteFile loop.
    The current change only covers the CopyFileEx path.
    If we decide to add it, the other one must be covered too, supposedly using FILE_FLAG_NO_BUFFERING.

    • There are certain requirements when working without buffering. We will need to ensure that memory buffers and file reads and writes are properly aligned, including when dealing with sparse files.
  2. "Large file" is a relative concept.
    1 GB file is probably "large" for a system with 4 GB RAM, but probably "nothing" for a system with 64 GB RAM.
    I doubt that an average user can figure out on their own where to draw the line.
    I suspect that an average user will most likely set it incorrectly, making things worse.
    If we decide to add it, the limit should probably be calculated automatically (e.g. 10-20% of RAM) and applied automatically without exposing any knobs to the user.

Спасибо за комментарий,

  1. да я понимаю что код содержит также ветку которая использует Read/Write цикл для копирования файла, но мне показалось что он оставлен только для уникальных случаев копирования, для 95% подходит ветка CopyFileEx
  2. да для этой ветки возможна реализация через FILE_FLAG_NO_BUFFERING, я это понимаю....
  3. если согласиться с Вами что 1GB файл не является "большим" в системе с 64GB памяти, то что можно будет сказать если я копирую 100 файлов по 1GB? при копировании в авто режиме (10-20% RAM) данные этих файлов забьют весь доступный кэш, тем самым вытеснят все пользовательские данные из кэша
  4. по моему коду видно, что я специально не стал запоминать выбор этой опции при повторном вызове диалога копирования/перемещения, это сделано специально, пользователь должен осознанно использовать эту функцию при копировании/перемещении файлов

@check4game
Copy link
Author

check4game commented Dec 4, 2023

в дополнение....

5 возможно использование предела размера файла в качестве переключателя было моим поспешным решением, потому как затеняет причину использования отключения системного кэша
6 моя идея в первую очередь была в том что бы быть уверенным что операция записи последнего блока файла будет где-то совсем рядом по времени после того как файл будет закрыт в Far, а не через несколько минут, после того как система завершит сброс страниц из кэша на диск, это особенно важно для операции MOVE
7 я знаю только консольные утилиты xcopy & robocopy которые позволяют это делать, но я уже много лет использую Far и считаю что он является оптимальным вариантом для работы с файлами на windows

@MKadaner
Copy link
Contributor

MKadaner commented Dec 5, 2023

6 моя идея в первую очередь была в том что бы быть уверенным что операция записи последнего блока файла будет где-то совсем рядом по времени после того как файл будет закрыт в Far, а не через несколько минут, после того как система завершит сброс страниц из кэша на диск, это особенно важно для операции MOVE

+1 for a control to ensure the completion of a write operation is sequenced before the closing of the dialog. Off by default of course. Also, a well-written explanation in the help topic(s) is a must (I can help here).

Now, I am not sure that synchronizing the completion of a write operation (main goal here?) and turning off system cache are synonymous. If Far performs an async I/O and closes the dialog as soon as writing of the last buffer was initiated (I do not know; did not check), the user still cannot be sure that the data were successfully written.

@check4game
Copy link
Author

я записал ролик, как ведет себя система при копировании файла без COPY_FILE_NO_BUFFERING и с COPY_FILE_NO_BUFFERING

https://www.youtube.com/watch?v=KPMpGOOyZXg

@check4game
Copy link
Author

Now, I am not sure that synchronizing the completion of a write operation (main goal here?) and turning off system cache are synonymous. If Far performs an async I/O and closes the dialog as soon as writing of the last buffer was initiated (I do not know; did not check), the user still cannot be sure that the data were successfully written.

1 да это не основная цель, хотя конечно можно рассмотреть и этот вариант для параноиков
2 по коду Far используется CopyFileEx или синхронные Read/Write

@alabuzhev
Copy link
Contributor

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

Yep, you're right. But by this logic manual limit doesn't make much sense too: there always can be too many "small" files.

Perhaps a single checkbox "Bypass write cache", not persisted anywhere, would be the optimal choice.

@check4game
Copy link
Author

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

Yep, you're right. But by this logic manual limit doesn't make much sense too: there always can be too many "small" files.

Perhaps a single checkbox "Bypass write cache", not persisted anywhere, would be the optimal choice.

да я тоже думаю что достаточно одного флага, без сохранения состояния.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants