01 /*
02 * Java Genetic Algorithm Library (jenetics-3.5.0).
03 * Copyright (c) 2007-2016 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
19 */
20 package org.jenetics.engine;
21
22 import static java.util.Objects.requireNonNull;
23
24 import java.time.Clock;
25 import java.time.Duration;
26 import java.util.function.Function;
27 import java.util.function.Supplier;
28
29 /**
30 * Container class which contains the execution result and the execution time.
31 *
32 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
33 * @since 3.0
34 * @version 3.0
35 */
36 final class TimedResult<T> {
37
38 final Duration duration;
39 final T result;
40
41 TimedResult(final Duration duration, final T result) {
42 this.duration = requireNonNull(duration);
43 this.result = requireNonNull(result);
44 }
45
46 /**
47 * Wraps the given supplier in a supplier which returns a {@code TimedResult}.
48 *
49 * @param supplier the supplier to wrap
50 * @param clock the clock used for measure the execution time
51 * @param <T> the result type
52 * @return the wrapped supplier which returns a {@code TimedResult}
53 */
54 public static <T> Supplier<TimedResult<T>> of(
55 final Supplier<? extends T> supplier,
56 final Clock clock
57 ) {
58 return () -> {
59 final Timer timer = Timer.of(clock).start();
60 final T result = supplier.get();
61 return new TimedResult<>(timer.stop().getTime(), result);
62 };
63 }
64
65 /**
66 * Wraps the given function in a function which returns a
67 * {@code TimedResult}.
68 *
69 * @param function the function to wrap
70 * @param clock the clock used for measure the execution time
71 * @param <T> the functions parameter type
72 * @param <R> the functions return type
73 * @return the wrapped function which returns a {@code TimedResult}
74 */
75 public static <T, R> Function<T, TimedResult<R>> of(
76 final Function<? super T, ? extends R> function,
77 final Clock clock
78 ) {
79 return value -> {
80 final Timer timer = Timer.of(clock).start();
81 final R result = function.apply(value);
82 return new TimedResult<>(timer.stop().getTime(), result);
83 };
84 }
85
86 }
|