1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.utils.datastructures;
14 import java.io.PrintStream;
15 import java.util.concurrent.TimeUnit;
16 import java.util.function.BiConsumer;
20 * @author Tuukka Lehtonen
22 public final class TimingUtil {
24 public abstract static class NamedRunnable implements Runnable {
26 public NamedRunnable(String name) {
30 public String toString() {
35 public static class PrintCallback implements BiConsumer<Long, TimeUnit> {
38 PrintCallback(String task) {
39 this(task, System.out);
41 PrintCallback(String task, PrintStream stream) {
46 public void accept(Long arg1, TimeUnit arg2) {
47 stream.println(task + " took " + arg1 + " " + arg2.toString());
51 public static void time(Runnable runnable) {
52 time(runnable, System.out);
55 public static void time(Runnable runnable, PrintStream stream) {
56 time(runnable, TimeUnit.MILLISECONDS, new PrintCallback(runnable.toString(), stream));
59 public static void time(Runnable runnable, TimeUnit reportTimeUnit, PrintStream stream) {
60 time(runnable, reportTimeUnit, new PrintCallback(runnable.toString(), stream));
63 public static void time(Runnable runnable, TimeUnit reportTimeUnit, BiConsumer<Long, TimeUnit> result) {
64 long start = System.nanoTime();
66 long end = System.nanoTime();
67 result.accept(reportTimeUnit.convert(end-start, TimeUnit.NANOSECONDS), reportTimeUnit);