1 /* 2 * Copyright (C) 2013 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.caliper.worker; 18 19 import static com.google.caliper.util.Reflection.getAnnotatedMethods; 20 import static java.util.concurrent.TimeUnit.NANOSECONDS; 21 22 import com.google.caliper.api.AfterRep; 23 import com.google.caliper.api.BeforeRep; 24 import com.google.caliper.model.Measurement; 25 import com.google.caliper.model.Value; 26 import com.google.caliper.runner.Running.Benchmark; 27 import com.google.caliper.runner.Running.BenchmarkMethod; 28 import com.google.caliper.util.Util; 29 import com.google.common.base.Stopwatch; 30 import com.google.common.base.Ticker; 31 import com.google.common.collect.ImmutableSet; 32 33 import java.lang.reflect.Method; 34 import java.util.Map; 35 36 import javax.inject.Inject; 37 38 /** 39 * The {@link Worker} implementation for macrobenchmarks. 40 */ 41 public class MacrobenchmarkWorker extends Worker { 42 private final Stopwatch stopwatch; 43 private final ImmutableSet<Method> beforeRepMethods; 44 private final ImmutableSet<Method> afterRepMethods; 45 private final boolean gcBeforeEach; 46 47 @Inject MacrobenchmarkWorker(@Benchmark Object benchmark, @BenchmarkMethod Method method, 48 Ticker ticker, @WorkerOptions Map<String, String> workerOptions) { 49 super(benchmark, method); 50 this.stopwatch = Stopwatch.createUnstarted(ticker); 51 this.beforeRepMethods = 52 getAnnotatedMethods(benchmark.getClass(), BeforeRep.class); 53 this.afterRepMethods = 54 getAnnotatedMethods(benchmark.getClass(), AfterRep.class); 55 this.gcBeforeEach = Boolean.parseBoolean(workerOptions.get("gcBeforeEach")); 56 } 57 58 @Override public void preMeasure(boolean inWarmup) throws Exception { 59 for (Method beforeRepMethod : beforeRepMethods) { 60 beforeRepMethod.invoke(benchmark); 61 } 62 if (gcBeforeEach && !inWarmup) { 63 Util.forceGc(); 64 } 65 } 66 67 @Override public Iterable<Measurement> measure() throws Exception { 68 stopwatch.start(); 69 benchmarkMethod.invoke(benchmark); 70 long nanos = stopwatch.stop().elapsed(NANOSECONDS); 71 stopwatch.reset(); 72 return ImmutableSet.of(new Measurement.Builder() 73 .description("runtime") 74 .weight(1) 75 .value(Value.create(nanos, "ns")) 76 .build()); 77 } 78 79 @Override public void postMeasure() throws Exception { 80 for (Method afterRepMethod : afterRepMethods) { 81 afterRepMethod.invoke(benchmark); 82 } 83 } 84 } 85