This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
PF3/hw2/Ex3/src/test/Tester.java

74 lines
2.3 KiB
Java

package test;
import util.PrimeCounter;
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 void setStrategy(PrimeCounter strategy) {
this.strategy = strategy;
}
private int countPrimes(int[] array) {
return new SequentialPrimeCounter().countPrimes(array);
}
private void testImplementation(int[] array, String name)
throws Exception {
long startTime = System.nanoTime();
int count = strategy.countPrimes(array);
long endTime = System.nanoTime();
long result = countPrimes(array);
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");
// TODO: Uncomment to test additional implementations
/*
// 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");
*/
}
}