我在评估我的 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);
}
}