【发布时间】:2011-05-22 15:12:08
【问题描述】:
我想弄清楚为什么“选择 A”比“选择 B”表现更好。我的测试显示类似 228 与 830 或差不多,这就像 4 倍的差异。看着 IL,未经训练的眼睛无法分辨出两个电话之间的细微差别。
谢谢你, 斯蒂芬
const int SIZE = 10000;
void Main()
{
var sw = Stopwatch.StartNew();
int[,]A = new int[SIZE, SIZE];
int total, x, y;
// Choice A
total = 0;
for (x = 0; x < SIZE; x++)
{
for (y = 0; y < SIZE; y++)
{
total += A[x, y];
}
}
Console.WriteLine(sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
// Choice B
total = 0;
for (y = 0; y < SIZE; y++)
{
for (x = 0; x < SIZE; x++)
{
total += A[x, y];
}
}
Console.WriteLine(sw.ElapsedMilliseconds);
}
// Define other methods and classes here
好的,我打破了这一点,以便它们彼此独立运行并减轻任何缓存和/或诊断...并且 B 总是落后于 A
namespace ConsoleApplication1
{
class ProgramA
{
const int SIZE = 10000;
static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
int[,] A = new int[SIZE, SIZE];
int total, x, y;
// Choice A
total = 0;
for (x = 0; x < SIZE; x++)
{
for (y = 0; y < SIZE; y++)
{
total += A[x, y];
}
}
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
}
}
class ProgramB
{
const int SIZE = 10000;
static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
int[,] A = new int[SIZE, SIZE];
int total, x, y;
// Choice B
total = 0;
for (y = 0; y < SIZE; y++)
{
for (x = 0; x < SIZE; x++)
{
total += A[x, y];
}
}
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
}
}
}
【问题讨论】:
-
我认为检测代码有点可疑,但我会希望 A 性能更好,因为它对缓存更友好。 stackoverflow.com/questions/763262/cache-efficient-code/…
-
在我的机器上运行相同的代码示例。选项 B 仅比选项 A 稍慢。选项 A = 1563 毫秒 选项 B = 2121 毫秒
-
哦,伙计,我几年前就看到过这个问题,但我不记得答案了。我认为这是因为第二个在每次迭代时都会创建一个新维度,而第一个已经有了第一个维度。
-
@Joseph:这两个选项之间的差异幅度可能与处理器高度相关。