]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.utils.datastructures/src/org/simantics/utils/datastructures/TimingUtil.java
Merge branch 'feature/funcwrite'
[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 import java.util.function.BiConsumer;
17
18
19 /**
20  * @author Tuukka Lehtonen
21  */
22 public final class TimingUtil {
23
24     public abstract static class NamedRunnable implements Runnable {
25         String name;
26         public NamedRunnable(String name) {
27             this.name = name;
28         }
29         @Override
30         public String toString() {
31             return name;
32         }
33     }
34
35     public static class PrintCallback implements BiConsumer<Long, TimeUnit> {
36         String task;
37         PrintStream stream;
38         PrintCallback(String task) {
39             this(task, System.out);
40         }
41         PrintCallback(String task, PrintStream stream) {
42             this.task = task;
43             this.stream = stream;
44         }
45         @Override
46         public void accept(Long arg1, TimeUnit arg2) {
47             stream.println(task + " took " + arg1 + " " + arg2.toString());
48         }
49     };
50
51     public static void time(Runnable runnable) {
52         time(runnable, System.out);
53     }
54
55     public static void time(Runnable runnable, PrintStream stream) {
56         time(runnable, TimeUnit.MILLISECONDS, new PrintCallback(runnable.toString(), stream));
57     }
58
59     public static void time(Runnable runnable, TimeUnit reportTimeUnit, PrintStream stream) {
60         time(runnable, reportTimeUnit, new PrintCallback(runnable.toString(), stream));
61     }
62
63     public static void time(Runnable runnable, TimeUnit reportTimeUnit, BiConsumer<Long, TimeUnit> result) {
64         long start = System.nanoTime();
65         runnable.run();
66         long end = System.nanoTime();
67         result.accept(reportTimeUnit.convert(end-start, TimeUnit.NANOSECONDS), reportTimeUnit);
68     }
69
70 }