酷壳上的一道面试题
又一个有趣的面试题里看到的一道题目,原因看过《深入计算机体系结构》应该就能明白。
题目如下
有两个相同功能代码如下,请在在A,B,C是什么的情况下,请给出三个原因case 1比case 2快,还有三个原因case 2会比case 1要执行的快。(不考虑编译器优化)
for (i=0; i<N; ++i){
A; B; C; } |
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);
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);