Skip to content

Instantly share code, notes, and snippets.

@buchgr
Created December 17, 2015 17:42
Show Gist options
  • Save buchgr/18eb11e6eb228b316b66 to your computer and use it in GitHub Desktop.
Save buchgr/18eb11e6eb228b316b66 to your computer and use it in GitHub Desktop.
Test accuracy of ScheduledThreadPoolExecutor.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
// Run with enough heap and -verbose:gc to make sure that GC is not running.
public class Main {
static final int RUNS = 10_000;
static final ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
static final List<Long> deltas = new ArrayList<>(RUNS);
static void doSchedule() {
deltas.clear();
for (int i = 0; i < RUNS; i++) {
service.schedule(new Runnable() {
final long start = System.nanoTime();
public void run() {
deltas.add(System.nanoTime() - start);
}
}, 1, TimeUnit.NANOSECONDS);
}
while (deltas.size() != RUNS) {
LockSupport.parkNanos(1000);
}
}
public static void main(String... args) {
// Run 100 warmups.
for (int i = 0; i < 100; i++) {
doSchedule();
}
LockSupport.parkNanos(1000_000_000);
doSchedule();
long max = 0, min = Long.MAX_VALUE, avg = 0, median = 0;
for (long delta : deltas) {
max = Math.max(max, delta);
min = Math.min(min, delta);
avg += delta;
}
avg /= RUNS;
Collections.sort(deltas);
median = deltas.get(deltas.size() / 2);
System.out.printf("max: %d, min: %d, avg: %d, median: %d, runs: %d\n", max, min, avg, median, RUNS);
service.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment