]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.utils.datastructures/src/org/simantics/utils/datastructures/TimingUtil.java
Make Write-interfaces as @FunctionalInterface for lambdas
[simantics/platform.git] / bundles / org.simantics.utils.datastructures / src / org / simantics / utils / datastructures / TimingUtil.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.utils.datastructures;
13
14 import java.io.PrintStream;
15 import java.util.concurrent.TimeUnit;
16
17
18 /**
19  * @author Tuukka Lehtonen
20  */
21 public final class TimingUtil {
22
23     public abstract static class NamedRunnable implements Runnable {
24         String name;
25         public NamedRunnable(String name) {
26             this.name = name;
27         }
28         @Override
29         public String toString() {
30             return name;
31         }
32     }
33
34     public static class PrintCallback implements BinaryCallback<Long, TimeUnit> {
35         String task;
36         PrintStream stream;
37         PrintCallback(String task) {
38             this(task, System.out);
39         }
40         PrintCallback(String task, PrintStream stream) {
41             this.task = task;
42             this.stream = stream;
43         }
44         @Override
45         public void run(Long arg1, TimeUnit arg2) {
46             stream.println(task + " took " + arg1 + " " + arg2.toString());
47         }
48     };
49
50     public static void time(Runnable runnable) {
51         time(runnable, System.out);
52     }
53
54     public static void time(Runnable runnable, PrintStream stream) {
55         time(runnable, TimeUnit.MILLISECONDS, new PrintCallback(runnable.toString(), stream));
56     }
57
58     public static void time(Runnable runnable, TimeUnit reportTimeUnit, PrintStream stream) {
59         time(runnable, reportTimeUnit, new PrintCallback(runnable.toString(), stream));
60     }
61
62     public static void time(Runnable runnable, TimeUnit reportTimeUnit, BinaryCallback<Long, TimeUnit> result) {
63         long start = System.nanoTime();
64         runnable.run();
65         long end = System.nanoTime();
66         result.run(reportTimeUnit.convert(end-start, TimeUnit.NANOSECONDS), reportTimeUnit);
67     }
68
69 }