C/C++ For循环语句的效率测试优化及运行时错误:Stack Overflow2015-05-21在多重循环中,如果有可能,应当将最长的循环放在最内层,最短的循环放在最外层,以减少CPU跨切循环层的次数。使用以下代码对嵌套For循环的效率进行测试验证:
// 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;}
运行结果: