Skip to content

Instantly share code, notes, and snippets.

@thefasttracker
Created November 27, 2022 12:24
Show Gist options
  • Select an option

  • Save thefasttracker/c4b323f02ec8afe757a5a3cdfed0f53a to your computer and use it in GitHub Desktop.

Select an option

Save thefasttracker/c4b323f02ec8afe757a5a3cdfed0f53a to your computer and use it in GitHub Desktop.
Timing concurrent execution Java
// Simple framework for timing concurrent execution
public static long time(Executor executor, int concurrency,
Runnable action) throws InterruptedException {
CountDownLatch ready = new CountDownLatch(concurrency);
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(concurrency);
for (int i = 0; i < concurrency; i++) {
executor.execute(() -> {
ready.countDown(); // Tell timer we're ready
try {
start.await(); // Wait till peers are ready
action.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
done.countDown(); // Tell timer we're done
}
}); }
ready.await(); // Wait for all workers to be ready long startNanos = System.nanoTime(); start.countDown(); // And they're off!
done.await(); // Wait for all workers to finish return System.nanoTime() - startNanos;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment