/** * Return a predicate, which will truncate the evolution stream if the GA * execution exceeds a given time duration. This predicate is (normally) * used as safety net, for guaranteed stream truncation. * * <pre>{@code * final Phenotype<DoubleGene, Double> result = engine.stream() * // Truncate the evolution stream after 5 "steady" generations. * .limit(bySteadyFitness(5)) * // The evolution will stop after maximal 500 ms. * .limit(byExecutionTime(Duration.ofMillis(500)) * .collect(toBestPhenotype()); * }</pre> * * @since 3.1 * * @param duration the duration after the evolution stream will be truncated * @return a predicate, which will truncate the evolution stream, based on * the exceeded execution time * @throws NullPointerException if the evolution {@code duration} is * {@code null} */ public static Predicate<Object> byExecutionTime(final Duration duration) { return byExecutionTime(duration, NanoClock.systemUTC()); }
@Test(dataProvider = "durations") public void test(final Integer millis) { final CountClock clock = new CountClock(); final Duration duration = Duration.ofMillis(millis); final AtomicInteger count = new AtomicInteger(); stream() .limit(Limits.byExecutionTime(duration, clock)) .forEach(s -> count.incrementAndGet()); Assert.assertEquals(count.get(), millis.intValue()); Assert.assertEquals(clock.count, count.get() + 1); }
public static void main(final String[] args) throws InterruptedException { final Runner<Long, BitGene, Double> runner = Runner.of( duration -> KNAPSACK, duration -> Limits.byExecutionTime(Duration.ofMillis(duration)), TRIAL_METER, Writer.text().map(Object::toString), Reader.text().map(Long::parseLong), args ); runner.start(); runner.join(); }