79 lines
2.5 KiB
Java
79 lines
2.5 KiB
Java
package test;
|
|
|
|
import parallel.StreamsPrimeCounter;
|
|
import util.PrimeCounter;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.stream.IntStream;
|
|
import parallel.CallablePrimeCounter;
|
|
import parallel.ThreadPoolPrimeCounter;
|
|
import sequential.SequentialPrimeCounter;
|
|
import parallel.ForkJoinPoolPrimeCounter;
|
|
|
|
public class Tester {
|
|
|
|
private static final int NUM_THREADS = 8;
|
|
public static final int LOW = 2;
|
|
public static final int HIGH = 11201609;
|
|
private PrimeCounter strategy;
|
|
private static Map<int[], Long> checkMap = new HashMap<>();
|
|
|
|
private void setStrategy(PrimeCounter strategy) {
|
|
this.strategy = strategy;
|
|
}
|
|
|
|
private long countPrimes(int[] array) {
|
|
return new SequentialPrimeCounter().countPrimes(array);
|
|
}
|
|
|
|
private void testImplementation(int[] array, String name)
|
|
throws Exception {
|
|
|
|
checkMap.computeIfAbsent(array, k -> countPrimes(array));
|
|
long result = checkMap.get(array);
|
|
|
|
long startTime = System.nanoTime();
|
|
int count = strategy.countPrimes(array);
|
|
long endTime = System.nanoTime();
|
|
|
|
if (count != result) {
|
|
// Informing if the implementation failed
|
|
System.err.printf("- ERROR: %s; Expected: %d; Found: %d\n",
|
|
name, result, count);
|
|
} else {
|
|
// Showing the time taken by the implementation
|
|
System.out.printf("- %s: %d prime numbers found, "
|
|
+ "elapsed time: %d ms\n" , name, count,
|
|
((endTime - startTime) / 1000000));
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
//Generating an integer array with numbers in the range from LOW to HIGH
|
|
int[] numbers = IntStream.rangeClosed(LOW, HIGH).toArray();
|
|
Tester tester = new Tester();
|
|
|
|
// Testing different implementations:
|
|
// Sequential implementation
|
|
tester.setStrategy(new SequentialPrimeCounter());
|
|
tester.testImplementation(numbers,"Sequential version");
|
|
|
|
// Parallel - Callable implementation
|
|
tester.setStrategy(new CallablePrimeCounter(NUM_THREADS));
|
|
tester.testImplementation(numbers, "Parallel - Callable version");
|
|
|
|
// Parallel - ThreadPool implementation
|
|
tester.setStrategy(new ThreadPoolPrimeCounter(NUM_THREADS));
|
|
tester.testImplementation(numbers, "Parallel - ThreadPool version");
|
|
|
|
// Parallel - ForkJoinPool implementation - Ex. 4
|
|
tester.setStrategy(new ForkJoinPoolPrimeCounter(NUM_THREADS));
|
|
tester.testImplementation(numbers, "Parallel - ForkJoinPool version");
|
|
|
|
// Parallel - Streams implementation - BONUS
|
|
tester.setStrategy(new StreamsPrimeCounter());
|
|
tester.testImplementation(numbers, "Parallel - Streams version");
|
|
}
|
|
}
|