• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package com.google.caliper.worker;
18 
19 import com.google.caliper.model.ArbitraryMeasurement;
20 import com.google.caliper.model.Measurement;
21 import com.google.caliper.model.Value;
22 import com.google.caliper.runner.Running.Benchmark;
23 import com.google.caliper.runner.Running.BenchmarkMethod;
24 import com.google.caliper.util.Util;
25 import com.google.common.collect.ImmutableSet;
26 
27 import java.lang.reflect.Method;
28 import java.util.Map;
29 
30 import javax.inject.Inject;
31 
32 /**
33  * Worker for arbitrary measurements.
34  */
35 public final class ArbitraryMeasurementWorker extends Worker {
36   private final Options options;
37   private final String unit;
38   private final String description;
39 
ArbitraryMeasurementWorker( @enchmark Object benchmark, @BenchmarkMethod Method method, @WorkerOptions Map<String, String> workerOptions)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 
preMeasure(boolean inWarmup)51   @Override public void preMeasure(boolean inWarmup) throws Exception {
52     if (options.gcBeforeEach && !inWarmup) {
53       Util.forceGc();
54     }
55   }
56 
measure()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 
Options(Map<String, String> options)69     Options(Map<String, String> options) {
70       this.gcBeforeEach = Boolean.parseBoolean(options.get("gcBeforeEach"));
71     }
72   }
73 }
74