1 /******************************************************************************* 2 * Copyright (c) 2009, 2021 Mountainminds GmbH & Co. KG and Contributors 3 * This program and the accompanying materials are made available under 4 * the terms of the Eclipse Public License 2.0 which is available at 5 * http://www.eclipse.org/legal/epl-2.0 6 * 7 * SPDX-License-Identifier: EPL-2.0 8 * 9 * Contributors: 10 * Marc R. Hoffmann - initial API and implementation 11 * 12 *******************************************************************************/ 13 package org.jacoco.core.test.perf; 14 15 import java.util.concurrent.Callable; 16 17 /** 18 * Base class for execution time test scenarios. 19 */ 20 public abstract class TimedScenario implements IPerfScenario { 21 22 private static final int RUNS = 10; 23 24 private final String description; 25 TimedScenario(final String description)26 protected TimedScenario(final String description) { 27 this.description = description; 28 } 29 run(final IPerfOutput output)30 public void run(final IPerfOutput output) throws Exception { 31 final long time = getMinimumTime(getInstrumentedCallable()); 32 final Callable<Void> refRunnable = getReferenceCallable(); 33 final long reftime; 34 if (refRunnable == null) { 35 reftime = IPerfOutput.NO_REFERENCE; 36 } else { 37 reftime = getMinimumTime(refRunnable); 38 } 39 output.writeTimeResult(description, time, reftime); 40 } 41 42 /** 43 * Runs the given subject several times and returns the minimum execution 44 * time. 45 * 46 * @param subject 47 * @return minimum execution time in nano seconds 48 * @throws Exception 49 */ getMinimumTime(final Callable<Void> subject)50 private long getMinimumTime(final Callable<Void> subject) throws Exception { 51 long min = Long.MAX_VALUE; 52 for (int i = 0; i < RUNS; i++) { 53 final long t = getTime(subject); 54 min = Math.min(min, t); 55 } 56 return min; 57 } 58 getTime(final Callable<Void> subject)59 private long getTime(final Callable<Void> subject) throws Exception { 60 long start = System.nanoTime(); 61 subject.call(); 62 return System.nanoTime() - start; 63 } 64 getInstrumentedCallable()65 protected abstract Callable<Void> getInstrumentedCallable() 66 throws Exception; 67 getReferenceCallable()68 protected Callable<Void> getReferenceCallable() throws Exception { 69 return null; 70 } 71 72 } 73