1/* 2 * Copyright (C) 2011 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 17package com.google.caliper.worker; 18 19import com.google.caliper.model.ArbitraryMeasurement; 20import com.google.caliper.model.Measurement; 21import com.google.caliper.model.Value; 22import com.google.caliper.runner.Running.Benchmark; 23import com.google.caliper.runner.Running.BenchmarkMethod; 24import com.google.caliper.util.Util; 25import com.google.common.collect.ImmutableSet; 26 27import java.lang.reflect.Method; 28import java.util.Map; 29 30import javax.inject.Inject; 31 32/** 33 * Worker for arbitrary measurements. 34 */ 35public final class ArbitraryMeasurementWorker extends Worker { 36 private final Options options; 37 private final String unit; 38 private final String description; 39 40 @Inject ArbitraryMeasurementWorker( 41 @Benchmark Object benchmark, 42 @BenchmarkMethod Method method, 43 @WorkerOptions Map<String, String> workerOptions) { 44 super(benchmark, method); 45 this.options = new Options(workerOptions); 46 ArbitraryMeasurement annotation = method.getAnnotation(ArbitraryMeasurement.class); 47 this.unit = annotation.units(); 48 this.description = annotation.description(); 49 } 50 51 @Override public void preMeasure(boolean inWarmup) throws Exception { 52 if (options.gcBeforeEach && !inWarmup) { 53 Util.forceGc(); 54 } 55 } 56 57 @Override public Iterable<Measurement> measure() throws Exception { 58 double measured = (Double) benchmarkMethod.invoke(benchmark); 59 return ImmutableSet.of(new Measurement.Builder() 60 .value(Value.create(measured, unit)) 61 .weight(1) 62 .description(description) 63 .build()); 64 } 65 66 private static class Options { 67 final boolean gcBeforeEach; 68 69 Options(Map<String, String> options) { 70 this.gcBeforeEach = Boolean.parseBoolean(options.get("gcBeforeEach")); 71 } 72 } 73} 74