同样的运算次数,for 循环的个数不同,开销也是不同的。 我表示很无知……求解释~ linux下代码: #include <iostream> #include <sys/time.h> #include <unistd.h> using namespace std; int main() { long s; struct timeval start, end; for (int k = 0; k < 20; k++){ //8 gettimeofday(&start, NULL); s = 0; for (int i = 0; i < 10; i ++) { for (int j = 0; j < 10; j ++) { for (int l = 0; l < 10; l ++) { for (int m = 0; m < 10; m ++) { for (int n = 0; n < 10; n ++) { for (int o = 0; o < 10; o ++) { for (int p = 0; p < 10; p ++) { for (int q = 0; q < 10; q ++) { s++; } } } } } } } } gettimeofday(&end, NULL); double span = end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec)/1000000.0; cout << span << endl; //4 gettimeofday(&start, NULL); s = 0; for (int i = 0; i < 100; i ++) { for (int j = 0; j < 100; j ++) { for (int l = 0; l < 100; l ++) { for (int m = 0; m < 100; m ++) { s++; } } } } gettimeofday(&end, NULL); span = end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec)/1000000.0; cout << span << endl; //2 gettimeofday(&start, NULL); s = 0; for (int i = 0; i < 10000; i ++) { for (int j = 0; j < 10000; j ++) { s++; } } gettimeofday(&end, NULL); span = end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec)/1000000.0; cout << span << endl; //1 gettimeofday(&start, NULL); s = 0; for (int i = 0; i < 100000000; i ++) { s++; } gettimeofday(&end, NULL); span = end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec)/1000000.0; cout << span << endl; } return 0; } 结果: 分析:同样的运算量,for循环越多,耗时越长。循环体为空,效果更明显