【发布时间】:2019-05-10 00:27:45
【问题描述】:
假设x 是第一个索引并且y 是第二个(由于缓存未命中较少),垂直扫描二维数组显然更快。
然而,令我惊讶的是,当我需要使用垂直条纹(条纹宽度为 3)来扫描阵列时,如果我垂直处理单个条纹,我得到的结果比我做它时差 5%水平。谁能解释一下这怎么可能?
(edit:实际上“垂直”方法中的数组访问确实更快,但是这种方法使用了更多的循环,这会减慢整体速度比我们从更少的缓存未命中获得的收益要多得多;请参阅答案)。
下面的代码只是一个示例,但是当我在 BenchmarkDotNet 中对扫描线填充算法实现中扫描数组的相同方法进行基准测试时,我得到了相同的性能差异。
这是我的 C# 基准测试:
private void ProcessVerticalStripesHorizontally(int[,] matrix)
{
int size = matrix.GetLength(0);
for (int x = 1; x < size - 1; x++)
{
for (int y = 0; y < size; y++)
{
// should be slowe because x is changed often
var value = matrix[x, y];
var valueLeft = matrix[x-1, y];
var valueRight = matrix[x+1, y];
}
}
}
private void ProcessVerticalStripesVertically(int[,] matrix)
{
int size = matrix.GetLength(0);
for (int x = 1; x < size-1; x++)
{
// should be faster because x doesn't change often
for (int y = 0; y < size; y++)
{
var value = matrix[x, y];
}
for (int y = 0; y < size; y++)
{
var valueLeft = matrix[x - 1, y];
}
for (int y = 0; y < size; y++)
{
var valueRight = matrix[x + 1, y];
}
}
}
[Test]
public void AccessToArrayTest()
{
int size = 5000;
var matrix = new int[size, size];
ProcessVerticalStripesHorizontally(matrix);
ProcessVerticalStripesVertically(matrix);
for (int run = 0; run < 5; run++)
{
Console.WriteLine("run " + run + ": ");
var stopwatch = Stopwatch.StartNew();
for (int iteration = 0; iteration < 5; iteration++)
{
ProcessVerticalStripesHorizontally(matrix);
}
Console.WriteLine("processing stripes horizontally: "
+ stopwatch.ElapsedMilliseconds + " ms");
stopwatch.Restart();
for (int iteration = 0; iteration < 5; iteration++)
{
ProcessVerticalStripesVertically(matrix);
}
Console.WriteLine("processing stripes vertically: "
+ stopwatch.ElapsedMilliseconds + " ms");
Console.WriteLine();
}
}
结果:
run 0:
processing stripes horizontally: 454 ms
processing stripes vertically: 468 ms
run 1:
processing stripes horizontally: 441 ms
processing stripes vertically: 456 ms
run 2:
processing stripes horizontally: 437 ms
processing stripes vertically: 453 ms
run 3:
processing stripes horizontally: 437 ms
processing stripes vertically: 456 ms
run 4:
processing stripes horizontally: 441 ms
processing stripes vertically: 449 ms
【问题讨论】:
-
这看起来像是一个本土基准。我不相信这些,尤其是当涉及到诸如缓存未命中之类的事情时。试试BenchmarkDotNet,尤其是结合performance counters。
-
嗨,据我所知;基准标记是一件相当复杂的事情,具有巨大的副作用。为了获得正确的基准,您应该排除编译器优化并查看“本机”输出。如果我查看您的代码,我认为优化器会尽量充分利用它。
-
话虽如此:我不确定您是如何阅读自己的代码并认为除了冗余循环之外,这些代码段实际上是不同的。
-
如果这段代码得到了适当的优化,它应该是一个很大的空操作,因为没有对读取的值做任何事情。
-
只有我一个人认为
y在我们将它放在 3 个不同的循环中时变化得更频繁,也许这就是它不同的原因?
标签: c# arrays performance multidimensional-array