/** * Time the given function multiple times. * * @param repeat the number of times to repeat the function call; must be positive * @param runnable the function to call; may not be null */ public default void time(int repeat, Runnable runnable) { for (int i = 0; i != repeat; ++i) { Stopwatch sw = create().start(); try { runnable.run(); } finally { sw.stop(); } } }
/** * Time the given function. * * @param runnable the function that is to be executed; may not be null * @return the result of the operation */ public default <T> T time(Callable<T> runnable) { Stopwatch sw = create().start(); try { return runnable.call(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } finally { sw.stop(); } }
/** * Time the given function multiple times. * * @param repeat the number of times to repeat the function call; must be positive * @param runnable the function that is to be executed a number of times; may not be null * @param cleanup the function that is to be called after each time call to the runnable * function, and not included in the time measurements; may be null * @throws Exception the exception thrown by the runnable function */ public default <T> void time(int repeat, Callable<T> runnable, Consumer<T> cleanup) throws Exception { for (int i = 0; i != repeat; ++i) { T result = null; Stopwatch sw = create().start(); try { result = runnable.call(); } finally { sw.stop(); if (cleanup != null) { cleanup.accept(result); } } } }