How to programmatically clear buffers and caches in Windows
Twisty is correct that there is no native tool in Windows to do this.
However, on doing some further research and testing, it seems that even SysInternals' Sync tool doesn't actually clear the memory used by Windows to cache files and data - otherwise known as the filesystem cache, and which Windows calls standby memory. This can be demonstrated by using RAMMap, another SysInternals tool that monitors all memory allocations in Windows.
Inspecting RAMMap's Standby Memory column before and after running the Sync
tool shows that Windows' standby memory remains virtually unchanged before and after running Sync
. In fact, Sync
doesn't seem to have any noticeable effect on memory at all, which as far as I can tell makes it essentially useless for the purposes of performance testing.
I did discover an effective programmatic method to clear Windows' standby list, however, in the form of EmptyStandbyList.exe, a simple command-line program from Wen Jia Liu:
EmptyStandbyList.exe is a command line tool for Windows (Vista and above) that can empty:
- process working sets
- the modified page list
- the standby lists (priorities 0 to 7)
- the priority 0 standby list only
To use it, you need to ensure the EmptyStandbyList.exe file is in a location within your system's PATH environment variable, then call EmptyStandbyList.exe
from the shell or from within a script when you need to flush memory.
In CMD
:
EmptyStandbyList.exe
And in bash
:
cmd \/c EmptyStandbyList.exe
To confirm that Windows' standby memory has been successfully cleared after execution, you can again use RAMMap.
Before running EmptyStandbyList.exe
After running EmptyStandbyList.exe
There is no equivalent command built-in to Windows. However Microsoft makes freely available the Sync command, which does what you ask as far as for flushing unwritten data to disk. It's part of the SysInternals suite of tools.
Here's the description from its author:
UNIX provides a standard utility called Sync, which can be used to direct the operating system to flush all file system data to disk in order to insure that it is stable and won't be lost in case of a system failure. Otherwise, any modified data present in the cache would be lost. Here is an equivalent that I wrote, called Sync, that works on all versions of Windows. Use it whenever you want to know that modified file data is safely stored on your hard drives.
You need administrative privileges to run the command. To flush the buffers of all disks, simply run:
sync
If you want to target only a single drive, such as C:
use:
sync c:
You can also flush only removable drives with:
sync -r
This utility works on all versions of Windows from Vista/Server 2008 onward.