/******************************************************************************* * Copyright (c) 2007, 2010 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.utils.datastructures; import java.io.PrintStream; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; /** * @author Tuukka Lehtonen */ public final class TimingUtil { public abstract static class NamedRunnable implements Runnable { String name; public NamedRunnable(String name) { this.name = name; } @Override public String toString() { return name; } } public static class PrintCallback implements BiConsumer { String task; PrintStream stream; PrintCallback(String task) { this(task, System.out); } PrintCallback(String task, PrintStream stream) { this.task = task; this.stream = stream; } @Override public void accept(Long arg1, TimeUnit arg2) { stream.println(task + " took " + arg1 + " " + arg2.toString()); } }; public static void time(Runnable runnable) { time(runnable, System.out); } public static void time(Runnable runnable, PrintStream stream) { time(runnable, TimeUnit.MILLISECONDS, new PrintCallback(runnable.toString(), stream)); } public static void time(Runnable runnable, TimeUnit reportTimeUnit, PrintStream stream) { time(runnable, reportTimeUnit, new PrintCallback(runnable.toString(), stream)); } public static void time(Runnable runnable, TimeUnit reportTimeUnit, BiConsumer result) { long start = System.nanoTime(); runnable.run(); long end = System.nanoTime(); result.accept(reportTimeUnit.convert(end-start, TimeUnit.NANOSECONDS), reportTimeUnit); } }