81,116
社区成员
发帖
与我相关
我的任务
分享
for(int i=0;i<1000;i++){
for(int j=0;j<100;j++){
for(int k=0;k<10;k++){
function(i,j,k);
}
}
}
for (int i = 0, j = 0, k = 0; i < 1000; k++) {
if (k >= 10) {
k = 0;
j++;
if (j >= 100) {
j = 0;
i++;
}
}
function(i,j,k);
}
不过好像没快多少,呵呵,快了两秒而已
for (int i = 0,j=0,k=0; i < 1000&& j<100; j++) {
if (j >= 100) {
j = 0;
i++;
if (k >= 10) {
k = 0;
j++;
}
function(i, j, k);
}
}
public static void main(String[] args) {
int x = 0;
for (int i = 0; i < 2; i++) {
System.out.println("compare i:" + i + " " + ++x);
for (int j = 0; j < 3; j++) {
System.out.println("compare j:" + j + " " + ++x);
for (int k = 0; k < 4; k++) {
System.out.println("compare k:" + k + " " + ++x);
}
}
}
System.out.println();
x = 0;
for (int i = 0; i < 4; i++) {
System.out.println("compare i:" + i + " " + ++x);
for (int j = 0; j < 3; j++) {
System.out.println("compare j:" + j + " " + ++x);
for (int k = 0; k < 2; k++) {
System.out.println("compare k:" + k + " " + ++x);
}
}
}
}
package com.jindie;
/**
* 优化下面的代码,并给出理由~
for(int i=0;i<1000;i++){
for(int j=0;j<100;j++){
for(int k=0;k<10;k++){
function(i,j,k);
}
}
}
* @author SnowFigure
*
*/
public class T201301 {
private static int count = 0;
private static void function(int i,int j,int k){
count ++;
}
public static void main(String[] args) {
int iMax = 1000;
int jMax = 100;
int kMax = 10;
int t = iMax * jMax * kMax;
// for(int i=0;i<t;i++){
// function(t/1000,t/100000,t%1000000);
// }
// for(int i=0;i<1000;i++){
// for(int j=0;j<100;j++){
// for(int k=0;k<10;k++){
// function(i,j,k);
// }
// }
// }
System.out.println(count);
}
}
欢迎指教
长见识了减小了栈切换的频率

减小了栈切换的频率
for(int i=0;i<1000;i++){ for(int j=0;j<100;j++){ for(int k=0;k<10;k++){ function(i,j,k); } } }
for(int k=0;k<10;k++){
for(int j=0;j<100;j++){
for(int i=0;i<1000;i++){
function(i,j,k);
}
}
}
上述代码中function执行次数一样,
但是k需要比较10次,j需要比较10*100次,i需要比较10*100*1000次。
总的比较次数是10+10*100+10*100*1000次
所以后面的代码比前面的代码少比较1000+1000*100-(10+10*100)次!循环数越多越放在里面层循环。