C/C++ For循環語句的效率測試優化及運行時錯誤:Stack Overflow的解決辦法
在多重循環中,如果有可能,應當將最長的循環放在最內層,最短的
循環放在最外層,以減少CPU跨切循環層的次數。
使用以下代碼對嵌套For循環的效率進行測試驗證:
[cpp]
// For嵌套性能.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
clock_t cstart,cends;
cstart=clock();
long sum1 =0;
long a1[5][10000000];
for(long i = 0; i < 5; i++)
{
for(long j = 0; j < 10000000; j++)
{
sum1 += a1[i][j];
}
}
cout << "sum1=:" << sum1 << endl;
cends=clock();
cout << "Clock時間差:" << cends-cstart << endl;
/////////////////////////////////////////////////////////////////
cstart=clock();
long sum =0;
long a[10000000][5];
for(i = 0; i < 10000000; i++)
{
for(long j = 0; j < 5; j++)
{
sum += a[i][j];
}
}
cout << "sum=:" << sum << endl;
cends=clock();
cout << "Clock時間差:" << cends-cstart << endl;
//////////////////////////////////////////////////////////////
system("pause");
return 0;
}
運行結果:
以上代碼在Windows Server 2008 x64 系統上編譯通過,
IDE為:Microsoft Visual c++ sp6
可以編譯通過,但是運行會出現錯誤:
運行時錯誤:Stack Overflow的解決辦法: