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;
19 * @author Tuukka Lehtonen
21 public final class TimingUtil {
23 public abstract static class NamedRunnable implements Runnable {
25 public NamedRunnable(String name) {
29 public String toString() {
34 public static class PrintCallback implements BinaryCallback<Long, TimeUnit> {
37 PrintCallback(String task) {
38 this(task, System.out);
40 PrintCallback(String task, PrintStream stream) {
45 public void run(Long arg1, TimeUnit arg2) {
46 stream.println(task + " took " + arg1 + " " + arg2.toString());
50 public static void time(Runnable runnable) {
51 time(runnable, System.out);
54 public static void time(Runnable runnable, PrintStream stream) {
55 time(runnable, TimeUnit.MILLISECONDS, new PrintCallback(runnable.toString(), stream));
58 public static void time(Runnable runnable, TimeUnit reportTimeUnit, PrintStream stream) {
59 time(runnable, reportTimeUnit, new PrintCallback(runnable.toString(), stream));
62 public static void time(Runnable runnable, TimeUnit reportTimeUnit, BinaryCallback<Long, TimeUnit> result) {
63 long start = System.nanoTime();
65 long end = System.nanoTime();
66 result.run(reportTimeUnit.convert(end-start, TimeUnit.NANOSECONDS), reportTimeUnit);