又一個有趣的面試題裡看到的一道題目,原因看過《深入電腦體繫結構》應該就能明白。
題目如下
有兩個相同功能代碼如下,請在在A,B,C是什麼的情況下,請給出三個原因case 1比case 2快,還有三個原因case 2會比case 1要執行的快。(不考慮編譯器最佳化)
case 1
|
for (i=0; i<N; ++i){ A; B; C; } |
case 2
|
for (i=0; i<N; ++i){ A; } for (i=0; i<N; ++i){ B; } for (i=0; i<N; ++i){ C; } |
我的解法
int length = 10000;
int[,] a = new int[
length ,
length ];
int[,] b = new int[length, length];
int[,] c = new int[length, length];
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < length; i++)
{
int temp = 0;
temp = a[i, i];
temp = b[i, i];
temp = c[i, i];
}
watch.Stop();
Console.WriteLine(“case 1:” + watch.ElapsedMilliseconds);
watch.Restart();
for (int i = 0; i < length; i++)
{
int temp = 0;
temp = a[i, i];
}
for (int i = 0; i < length; i++)
{
int temp = 0;
temp = b[i, i];
}
for (int i = 0; i < length; i++)
{
int temp = 0;
temp = c[i, i];
}
watch.Stop();
Console.WriteLine(“case 2:” + watch.ElapsedMilliseconds);