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/Ex2/src/Tester.java

94 lines
2.8 KiB
Java

import java.util.concurrent.CountDownLatch;
public class Tester {
private static final int NUM_THREADS = 1024;
private static final int NUM_ITERATIONS = 64;
private static final int OCCUR = 32;
private final VoteCounter counter;
private final CountDownLatch threadsReady,
measurementStarted, threadsCompleted;
private class TesterThread extends Thread {
private final int startValue;
TesterThread(int startValue) {
this.startValue = startValue;
}
public void run() {
int iter = NUM_ITERATIONS * OCCUR;
int nextValue = startValue;
threadsReady.countDown();
try {
measurementStarted.await();
}
catch (InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
for (int i = 0; i < iter; i++) {
counter.addVote(nextValue);
nextValue = (nextValue + 1) % NUM_ITERATIONS;
}
threadsCompleted.countDown();
}
}
public Tester(VoteCounter counter) {
this.counter = counter;
this.threadsReady = new CountDownLatch(NUM_THREADS);
this.measurementStarted = new CountDownLatch(1);
this.threadsCompleted = new CountDownLatch(NUM_THREADS);
}
private long runMeasurement() throws InterruptedException {
for (int i = 0; i < NUM_THREADS; ++i) {
Thread t = new TesterThread( NUM_ITERATIONS / 2);
t.start();
}
threadsReady.await();
long timeBegin = System.nanoTime();
measurementStarted.countDown();
threadsCompleted.await();
long timeEnd = System.nanoTime();
return timeEnd - timeBegin;
}
private void check() {
int expectedOccur = OCCUR * NUM_THREADS;
for (int i = 0; i < NUM_ITERATIONS; i++) {
int foundOccur;
if ((foundOccur = counter.getVoteCount(i)) != expectedOccur) {
System.err.printf(" - ERROR: Expected: %d ; Found: %d\n",
expectedOccur, foundOccur);
}
}
}
private static void testImplementation(ConcurrentVoteCounter implementation,
String name) throws Exception {
System.out.println("Results for implementation: " + name);
Tester tester = new Tester(implementation);
long elapsedTime = tester.runMeasurement();
tester.check();
System.out.printf(" - Test completed, elapsed time: %d ms\n",
(elapsedTime / 1000000));
}
public static void main(String[] args) throws Exception {
//testImplementation(new BinTreeSimple(), "Simple version");
testImplementation(new ConcurrentVoteCounter(), "Concurrent version (correct)");
}
}