У меня есть большая проблема при оценке моего java-кода. Чтобы упростить задачу, я написал следующий код, который вызывает одно и то же любопытное поведение. Важным является метод run() и заданный коэффициент двойного значения. Для моего теста времени выполнения (в основном методе) я устанавливал скорость 0,5 раза и 1,0 в другое время. При значении 1.0 if-statement будет выполняться в каждой итерации цикла и со значением 0.5, if-statement будет выполняться в два раза меньше. По этой причине я ожидал более продолжительное время выполнения в первом случае, но наоборот. Может ли кто-нибудь объяснить мне это явление?
Результат main:
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);
}
}