更快的无限循环

时间:2017-04-16 12:58:31

标签: java performance for-loop while-loop

我编写了这个java循环来模拟某些基准测试的数据源。使用TimerTask计算每秒的增量计数值。这可以在我的笔记本电脑上执行大约500,000,000而无需循环工作:

int count = 0;
while (true) {
    count++;
}

但我偶尔会注意到这样的循环甚至可以达到40,000,000,000!

final int LOOP = 1000000;
while (true) {
    for (int i = 0; i < LOOP; i++) {
        count++;
    }
}

我测试过任何大于1的LOOP值都可以显着提升性能,或者写出更多的&#34; count ++;&#34;在while循环中而不是for循环。我完全糊涂了,有什么想法吗?

我查看了两者的字节码,发现后面的循环甚至做了更多的指令,我使用&#34; -XX:+ PrintCompilation&#34;并没有发现很大的区别。有没有什么东西,除了JIT编译器会做一些花哨的性能优化技巧?

我使用此工具测量速度:

public class ThroughputPeriodProbe extends TimerTask implements ThroughputProbe {

private static final long PERIOD = TimeUnit.SECONDS.toMillis(1);

private static Timer timer = new Timer("THROUHPUT_PROBE");

@Override
public void through() {
    amount++;
}

@Override
public void run() {
    final long currentAmount = amount;
    long delta = currentAmount - lastAmount;
    final long rate = (long) ((delta / (double) PERIOD) * 1000);
    System.out.println(name + ": " + rate);
    lastAmount = currentAmount;
}

public ThroughputPeriodProbe(final String name) {
    this.name = name;
    timer.scheduleAtFixedRate(this, 0, PERIOD);
}

/** The Last amount. */
private long lastAmount;

/** The Sum. */
private long amount;

/** The Name. */
private final String name;
}

像这样使用:

private ThroughputProbe count = new ThroughputPeriodProbe("Count");

while (true) {
    count.through();
}

0 个答案:

没有答案