【发布时间】:2013-07-31 22:46:55
【问题描述】:
给定以下测试代码(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 分钟。
我的问题是:使用内存映射文件时,“真实”内存是否会被使用?被占用的不只是虚拟地址空间吗?
我正在尝试了解使用内存映射文件时的物理内存消耗。
【问题讨论】: