Java コードの評価中に大きな問題が発生しました。問題を単純化するために、同じ奇妙な動作を生成する次のコードを書きました。重要なのは、メソッド run() と指定された double 値レートです。実行時テスト (メイン メソッド内) では、レートを 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);
}
}