近空Java For-Loop行为奇怪 [英] Near empty Java For-Loop acts strange

查看:142
本文介绍了近空Java For-Loop行为奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码作为预期打印平均运行次数:0.99864197

This code acts as expected printing "Average Number of Runs: 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);

    }
}

应该打印相同的代码确切的数字,而是打印一个随机的负数。

This code that should print the same exact number, but instead it prints a random negative number.

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循环?

Is there some optimization that happens in java for loops?

注意:


  1. 我使用的是jdk1.6.0 _45。

  2. 在正常使用情况下,新的随机将有一个更好的种子。

  3. 最小和最大值应该是任何数字。 >
  1. I'm using jdk1.6.0_45.
  2. In normal usage the new Random would have a better seed.
  3. min and max should be able to be any number.


推荐答案

我相信这是JIT处理一些Java版本中非常严格的循环的错误6.它可以 bug 6196102 或错误 6357124

I believe this to be a bug in the JIT handling of very tight loops in some versions of Java 6. It may be either bug 6196102 or bug 6357124.

更新到Java 7应该可以工作,虽然我明白,在你的情况下并没有多少帮助。你可能会发现,添加一个看起来不是一个不起作用,但是你不关心的东西你的循环中的方法调用也解决了问题。例如,您可以将 i 的所有值进行求和,然后将其打印到某些诊断日志中,以便忽略。

Updating to Java 7 should work, although I appreciate that doesn't help much in your situation. You may find that adding a "looks like it isn't a no-op, but does something you don't care about" method call within your loop fixes the problem too. For example, you could sum all the values of i, and print that to some diagnostic log afterwards to be ignored.

这篇关于近空Java For-Loop行为奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆