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