Jas*_*ore 12 .net c# arrays performance cpu-cache
我试图了解.NET世界中的CPU缓存性能.具体来说,我正在研究Igor Ostovsky 关于处理器缓存效果的文章.
我在他的文章中经历了前三个例子,并记录了与他的文章大不相同的结果.我想我一定做错了,因为我机器上的表现几乎与他在文章中所表现出来的结果完全相反.我没有看到我期望的缓存未命中的巨大影响.
我究竟做错了什么?(错误代码,编译器设置等)
以下是我机器上的性能结果:



如果有帮助,我机器上的处理器是Intel Core i7-2630QM.这是关于我的处理器缓存的信息:

我已经在x64 Release模式下编译了.
以下是我的源代码:
class Program
{
static Stopwatch watch = new Stopwatch();
static int[] arr = new int[64 * 1024 * 1024];
static void Main(string[] args)
{
Example1();
Example2();
Example3();
Console.ReadLine();
}
static void Example1()
{
Console.WriteLine("Example 1:");
// Loop 1
watch.Restart();
for (int i = 0; i < arr.Length; i++) arr[i] *= 3;
watch.Stop();
Console.WriteLine(" Loop 1: " + watch.ElapsedMilliseconds.ToString() + " ms");
// Loop 2
watch.Restart();
for (int i = 0; i < arr.Length; i += 32) arr[i] *= 3;
watch.Stop();
Console.WriteLine(" Loop 2: " + watch.ElapsedMilliseconds.ToString() + " ms");
Console.WriteLine();
}
static void Example2()
{
Console.WriteLine("Example 2:");
for (int k = 1; k <= 1024; k *= 2)
{
watch.Restart();
for (int i = 0; i < arr.Length; i += k) arr[i] *= 3;
watch.Stop();
Console.WriteLine(" K = "+ k + ": " + watch.ElapsedMilliseconds.ToString() + " ms");
}
Console.WriteLine();
}
static void Example3()
{
Console.WriteLine("Example 3:");
for (int k = 1; k <= 1024*1024; k *= 2)
{
//256* 4bytes per 32 bit int * k = k Kilobytes
arr = new int[256*k];
int steps = 64 * 1024 * 1024; // Arbitrary number of steps
int lengthMod = arr.Length - 1;
watch.Restart();
for (int i = 0; i < steps; i++)
{
arr[(i * 16) & lengthMod]++; // (x & lengthMod) is equal to (x % arr.Length)
}
watch.Stop();
Console.WriteLine(" Array size = " + arr.Length * 4 + " bytes: " + (int)(watch.Elapsed.TotalMilliseconds * 1000000.0 / arr.Length) + " nanoseconds per element");
}
Console.WriteLine();
}
}
Run Code Online (Sandbox Code Playgroud)
为什么在第二个循环中使用 i += 32 。您正在以这种方式跨过缓存线。32*4 = 128 字节比所需的 64 字节大得多。