In Java, C, or C++, how to write an unoptimized code to calculate the sum of 10 integers (from 0 to 9) programmatically?
For example, I use the following code but it is seems that both codes (the ones labeled as //Baseline and //Method #1) are optimized by the compiler at the compile time and the total variables are converted to constants before runtime. I confirmed that by comparing the time1 and time2 which are similar.
My question is:
Programmatically, how to sum the 10 numbers and force the compiler not to optimize the code (no constant propagation/folding, for example) to avoid calculating the sum at compile time and force it to happen only at runtime?
long start, end, time1, time2, total;
//Baseline
start = System.nanoTime();
total = (0+1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9);
end = System.nanoTime();
System.out.println("********************* The sum is " + total);
time1 = end - start;
System.out.println("********************* start=" + start + " end=" + end + " time=" + time1);
//Method #1
start = System.nanoTime();
total = (a0() + a1() + a2() + a3() + a4() + a5() + a6() + a7() + a8() + a9());
end = System.nanoTime();
System.out.println("********************* The sum is " + total);
time2 = end - start;
System.out.println("********************* start=" + start + " end=" + end + " time=" + time2);
}
private int a0()
{
return 0;
}
private int a1()
{
return 1;
}
private int a2()
{
return 2;
}
private int a3()
{
return 3;
}
private int a4()
{
return 4;
}
private int a5()
{
return 5;
}
private int a6()
{
return 6;
}
private int a7()
{
return 7;
}
private int a8()
{
return 8;
}
private int a9()
{
return 9;
}
Updated Requirements:
(1) Only for Java using Dalvik compiler
(2) Only primitive variables but nested functions (methods) are acceptable
(3) No volatile
(4) No loop, jump, or wait statements
By the way, I tried the suggested C and C++ suggestions below but non of them seem to work with Dalvik compiler where it converts the addition expression to a constant.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…