此代码按预期打印“平均运行次数:0.99864197”
import java.util.Random;
public class A {
public static void main(String[] args) {
int min = -30;
int max = 1;
test(min, max);
}
static void test(int min, int max){
int count = 0;
Random rand = new Random(0);
for(int j = 0; j < 2097152; j++){
int number = min + rand.nextInt(max-min+1);
for(int i = 0; i < number; ++i) {
System.out.print("");
count++;
}
}
System.out.println("Average Number of Runs: " + count/65536F);
}
}
该代码应该打印相同的精确数字,但它打印一个随机负数。
import java.util.Random;
public class A {
public static void main(String[] args) {
int min = -30;
int max = 1;
test(min, max);
}
static void test(int min, int max){
int count = 0;
Random rand = new Random(0);
for(int j = 0; j < 2097152; j++){
int number = min + rand.nextInt(max-min+1);
for(int i = 0; i < number; ++i) {
//System.out.print("");
count++;
}
}
System.out.println("Average Number of Runs: " + count/65536F);
}
}
java for 循环中是否有一些优化?
Notes:
- 我使用的是jdk1.6.0_45。
- 在正常使用中,新的 Random 会有更好的种子。
- min 和 max 应该可以是任意数字。
我相信这是 Java 6 某些版本中对非常紧密循环的 JIT 处理中的一个错误。may要么错误 6196102 https://bugs.java.com/bugdatabase/view_bug?bug_id=6196102 or bug 6357124 https://bugs.java.com/bugdatabase/view_bug?bug_id=6357214.
更新到 Java 7 应该可以,尽管我知道这对您的情况没有多大帮助。您可能会发现,在循环中添加“看起来不是无操作,但执行了您不关心的操作”方法调用也可以解决问题。例如,您可以将所有值相加i
,然后将其打印到某些诊断日志中以供忽略。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)