Created
November 27, 2022 12:24
-
-
Save thefasttracker/c4b323f02ec8afe757a5a3cdfed0f53a to your computer and use it in GitHub Desktop.
Timing concurrent execution Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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