假设有以下测试代码(x64环境):
static void Test()
{
string fileName = @"d:\map";
long length = new FileInfo(fileName).Length;
using (var file = MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, "mapFile", length, MemoryMappedFileAccess.ReadWrite))
{
byte* bytePtr = (byte*)0;
var view = file.CreateViewAccessor(0, length, MemoryMappedFileAccess.ReadWrite);
view.SafeMemoryMappedViewHandle.AcquirePointer(ref bytePtr);
long count = (long)(length / sizeof(int));
long sum = 0;
long step = count / 2000;
int* ptr = (int*)&bytePtr[0];
long currentCount = 0 ;
Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = 8 }, (i) =>
{
Interlocked.Add(ref sum, ptr[i]);
Interlocked.Increment(ref currentCount) ;
if (currentCount % step == 0)
Console.Write("\r{0:0.00}%", (100 * currentCount / (float)count));
});
Console.WriteLine(sum);
view.Dispose();
}
}
考虑到"d:\map"是一个40GB的文件,在通过指针"ptr"随机访问时,会出现非常奇怪的行为。系统物理内存被完全使用,一切都变得缓慢,该过程需要超过2个小时才能完成。
当我进行顺序(单线程)访问时,使用的物理内存不超过1GB,该进程大约需要8分钟。
我的问题是:使用内存映射文件时,是否使用“真实”的内存?难道不仅仅是占用虚拟地址空间吗?
我正在尝试了解使用内存映射文件时的物理内存消耗情况。