When the number of iterations is the same, I wonder if the smaller iterations of the outer 'for loop' are faster.
This is my java code.
total loops iterations is 100 billion.
public class Test {
public static long run1() {
final long start = System.nanoTime();
long cnt = 0;
for(int i = 0; i<1000000000; i++) {
for(int j = 0 ; j<100 ; j++) {
cnt++;
}
}
final long end = System.nanoTime();
System.out.println("run1 : "+(end-start)*1e-9+" sec");
return start - end;
}
public static long run2() {
final long start = System.nanoTime();
long cnt = 0;
for(int i = 0; i<100; i++) {
for(int j = 0 ; j<1000000000 ; j++) {
cnt++;
}
}
final long end = System.nanoTime();
System.out.println("run2 : "+(end-start)*1e-9+" sec");
return start - end;
}
public static void main(String[] args) {
for(int i = 0 ; i < 10 ; i++) {
long test1 = run1();
long test2 = run2();
System.out.println("Time diff : "+(test1-test2)*1e-9+" sec\n");
}
}
}
and this is result
run1 : 4.5772473950000006 sec
run2 : 1.7155700900000002 sec
Time diff : -2.861677305 sec
run1 : 4.4107229420000005 sec
run2 : 1.6532413140000002 sec
Time diff : -2.7574816280000003 sec
run1 : 3.815836296 sec
run2 : 1.761153921 sec
Time diff : -2.054682375 sec
run1 : 3.913543021 sec
run2 : 1.752971717 sec
Time diff : -2.1605713040000003 sec
run1 : 3.851766485 sec
run2 : 1.7262416440000001 sec
Time diff : -2.1255248410000003 sec
run1 : 3.95305219 sec
run2 : 1.7323067330000002 sec
Time diff : -2.220745457 sec
run1 : 3.924869236 sec
run2 : 1.6953032440000002 sec
Time diff : -2.229565992 sec
run1 : 3.839871705 sec
run2 : 1.692300162 sec
Time diff : -2.147571543 sec
run1 : 3.93864626 sec
run2 : 1.704322469 sec
Time diff : -2.234323791 sec
run1 : 3.863758493 sec
run2 : 1.700392962 sec
Time diff : -2.163365531 sec
like this,
I wonder why these results are coming.
and, edited by Triple nested loops, Similar results are obtained.