gpt4 book ai didi

Java 好奇循环性能

转载 作者:搜寻专家 更新时间:2023-10-30 21:04:25 25 4
gpt4 key购买 nike

我在评估我的 Java 代码时遇到了一个大问题。为了简化问题,我编写了以下代码,它们产生了同样奇怪的行为。重要的是方法 run() 和给定的双倍值率。对于我的运行时测试(在 main 方法中),我将速率一次设置为 0.5,另一次设置为 1.0。值为 1.0 时,if 语句将在每次循环迭代中执行,值为 0.5 时,if 语句将执行一半。出于这个原因,我预计第一种情况的运行时间会更长,但事实恰恰相反。谁能给我解释一下这个现象??

主要结果:

Test mit rate = 0.5
Length: 50000000, IF executions: 25000856
Execution time was 4329 ms.
Length: 50000000, IF executions: 24999141
Execution time was 4307 ms.
Length: 50000000, IF executions: 25001582
Execution time was 4223 ms.
Length: 50000000, IF executions: 25000694
Execution time was 4328 ms.
Length: 50000000, IF executions: 25004766
Execution time was 4346 ms.
=================================
Test mit rate = 1.0
Length: 50000000, IF executions: 50000000
Execution time was 3482 ms.
Length: 50000000, IF executions: 50000000
Execution time was 3572 ms.
Length: 50000000, IF executions: 50000000
Execution time was 3529 ms.
Length: 50000000, IF executions: 50000000
Execution time was 3479 ms.
Length: 50000000, IF executions: 50000000
Execution time was 3473 ms.

代码

public ArrayList<Byte> list = new ArrayList<Byte>();
public final int LENGTH = 50000000;

public PerformanceTest(){
byte[]arr = new byte[LENGTH];
Random random = new Random();
random.nextBytes(arr);
for(byte b : arr)
list.add(b);
}

public void run(double rate){

byte b = 0;
int count = 0;

for (int i = 0; i < LENGTH; i++) {

if(getRate(rate)){
list.set(i, b);
count++;
}
}
System.out.println("Length: " + LENGTH + ", IF executions: " + count);
}

public boolean getRate(double rate){
return Math.random() < rate;
}

public static void main(String[] args) throws InterruptedException {
PerformanceTest test = new PerformanceTest();

long start, end;
System.out.println("Test mit rate = 0.5");
for (int i = 0; i < 5; i++) {
start=System.currentTimeMillis();
test.run(0.5);
end = System.currentTimeMillis();
System.out.println("Execution time was "+(end-start)+" ms.");

Thread.sleep(500);
}
System.out.println("=================================");
System.out.println("Test mit rate = 1.0");
for (int i = 0; i < 5; i++) {
start=System.currentTimeMillis();
test.run(1.0);
end = System.currentTimeMillis();
System.out.println("Execution time was "+(end-start)+" ms.");
Thread.sleep(500);
}
}

最佳答案

在第一种情况下,分支预测错误会破坏性能。尽管第二种情况做了一些工作,但它有点简单,因此处理器可以轻松预测下一步。请看这个Wikipedia page获取更多信息。

尝试使用 0.7 进行测试。如果我是正确的,那么性能将介于 0.5 和 1.0 之间。

关于Java 好奇循环性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12479798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com