aboutsummaryrefslogtreecommitdiff
path: root/caliper/src/main/java/com/google/caliper/runner/ExperimentingCaliperRun.java
blob: e57e1b06a1934e74486ce100f9eeb63aad77d720 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*
 * Copyright (C) 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.caliper.runner;

import static java.util.logging.Level.WARNING;

import com.google.caliper.api.ResultProcessor;
import com.google.caliper.api.SkipThisScenarioException;
import com.google.caliper.options.CaliperOptions;
import com.google.caliper.util.Stdout;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Stopwatch;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.Uninterruptibles;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.inject.Provider;

/**
 * An execution of each {@link Experiment} for the configured number of trials.
 */
@VisibleForTesting
public final class ExperimentingCaliperRun implements CaliperRun {

  private static final Logger logger = Logger.getLogger(ExperimentingCaliperRun.class.getName());

  private static final AsyncFunction<Throwable, Object> FALLBACK_TO_NULL = new AsyncFunction<Throwable, Object>() {
    final ListenableFuture<Object> nullFuture = Futures.immediateFuture(null);
    @Override public ListenableFuture<Object> apply(Throwable t) throws Exception {
      return nullFuture;
    }
  };

  private final MainComponent mainComponent;
  private final CaliperOptions options;
  private final PrintWriter stdout;
  private final BenchmarkClass benchmarkClass;
  private final ImmutableSet<Instrument> instruments;
  private final ImmutableSet<ResultProcessor> resultProcessors;
  private final ExperimentSelector selector;
  private final Provider<ListeningExecutorService> executorProvider;

  @Inject @VisibleForTesting
  public ExperimentingCaliperRun(
      MainComponent mainComponent,
      CaliperOptions options,
      @Stdout PrintWriter stdout,
      BenchmarkClass benchmarkClass,
      ImmutableSet<Instrument> instruments,
      ImmutableSet<ResultProcessor> resultProcessors,
      ExperimentSelector selector,
      Provider<ListeningExecutorService> executorProvider) {
    this.mainComponent = mainComponent;
    this.options = options;
    this.stdout = stdout;
    this.benchmarkClass = benchmarkClass;
    this.instruments = instruments;
    this.resultProcessors = resultProcessors;
    this.selector = selector;
    this.executorProvider = executorProvider;
  }

  @Override
  public void run() throws InvalidBenchmarkException {
    ImmutableSet<Experiment> allExperiments = selector.selectExperiments();
    // TODO(lukes): move this standard-out handling into the ConsoleOutput class?
    stdout.println("Experiment selection: ");
    stdout.println("  Benchmark Methods:   " + FluentIterable.from(allExperiments)
        .transform(new Function<Experiment, String>() {
          @Override public String apply(Experiment experiment) {
            return experiment.instrumentation().benchmarkMethod().getName();
          }
        }).toSet());
    stdout.println("  Instruments:   " + FluentIterable.from(selector.instruments())
        .transform(new Function<Instrument, String>() {
              @Override public String apply(Instrument instrument) {
                return instrument.name();
              }
            }));
    stdout.println("  User parameters:   " + selector.userParameters());
    stdout.println("  Virtual machines:  " + FluentIterable.from(selector.vms())
        .transform(
            new Function<VirtualMachine, String>() {
              @Override public String apply(VirtualMachine vm) {
                return vm.name;
              }
            }));
    stdout.println("  Selection type:    " + selector.selectionType());
    stdout.println();

    if (allExperiments.isEmpty()) {
      throw new InvalidBenchmarkException(
          "There were no experiments to be performed for the class %s using the instruments %s",
          benchmarkClass.benchmarkClass().getSimpleName(), instruments);
    }

    stdout.format("This selection yields %s experiments.%n", allExperiments.size());
    stdout.flush();

    // always dry run first.
    ImmutableSet<Experiment> experimentsToRun = dryRun(allExperiments);
    if (experimentsToRun.size() != allExperiments.size()) {
      stdout.format("%d experiments were skipped.%n",
          allExperiments.size() - experimentsToRun.size());
    }

    if (experimentsToRun.isEmpty()) {
      throw new InvalidBenchmarkException("All experiments were skipped.");
    }

    if (options.dryRun()) {
      return;
    }

    stdout.flush();

    int totalTrials = experimentsToRun.size() * options.trialsPerScenario();
    Stopwatch stopwatch = Stopwatch.createStarted();
    List<ScheduledTrial> trials = createScheduledTrials(experimentsToRun, totalTrials);

    final ListeningExecutorService executor = executorProvider.get();
    List<ListenableFuture<TrialResult>> pendingTrials = scheduleTrials(trials, executor);
    ConsoleOutput output = new ConsoleOutput(stdout, totalTrials, stopwatch);
    try {
      // Process results as they complete.
      for (ListenableFuture<TrialResult> trialFuture : inCompletionOrder(pendingTrials)) {
        try {
          TrialResult result = trialFuture.get();
          output.processTrial(result);
          for (ResultProcessor resultProcessor : resultProcessors) {
            resultProcessor.processTrial(result.getTrial());
          }
        } catch (ExecutionException e) {
          if (e.getCause() instanceof TrialFailureException) {
            output.processFailedTrial((TrialFailureException) e.getCause());
          } else {
            for (ListenableFuture<?> toCancel : pendingTrials) {
              toCancel.cancel(true);
            }
            throw Throwables.propagate(e.getCause());
          }
        } catch (InterruptedException e) {
          // be responsive to interruption, cancel outstanding work and exit
          for (ListenableFuture<?> toCancel : pendingTrials) {
            // N.B. TrialRunLoop is responsive to interruption.
            toCancel.cancel(true);
          }
          throw new RuntimeException(e);
        }
      }
    } finally {
      executor.shutdown();
      output.close();
    }

    for (ResultProcessor resultProcessor : resultProcessors) {
      try {
        resultProcessor.close();
      } catch (IOException e) {
        logger.log(WARNING, "Could not close a result processor: " + resultProcessor, e);
      }
    }
  }

  /**
   * Schedule all the trials.
   *
   * <p>This method arranges all the {@link ScheduledTrial trials} to run according to their
   * scheduling criteria.  The executor instance is responsible for enforcing max parallelism.
   */
  private List<ListenableFuture<TrialResult>> scheduleTrials(List<ScheduledTrial> trials,
      final ListeningExecutorService executor) {
    List<ListenableFuture<TrialResult>> pendingTrials = Lists.newArrayList();
    List<ScheduledTrial> serialTrials = Lists.newArrayList();
    for (final ScheduledTrial scheduledTrial : trials) {
      if (scheduledTrial.policy() == TrialSchedulingPolicy.PARALLEL) {
        pendingTrials.add(executor.submit(scheduledTrial.trialTask()));
      } else {
        serialTrials.add(scheduledTrial);
      }
    }
    // A future representing the completion of all prior tasks. Futures.successfulAsList allows us
    // to ignore failure.
    ListenableFuture<?> previous = Futures.successfulAsList(pendingTrials);
    for (final ScheduledTrial scheduledTrial : serialTrials) {
      // each of these trials can only start after all prior trials have finished, so we use
      // Futures.transform to force the sequencing.
      ListenableFuture<TrialResult> current =
          Futures.transformAsync(
              previous,
              new AsyncFunction<Object, TrialResult>() {
                @Override public ListenableFuture<TrialResult> apply(Object ignored) {
                  return executor.submit(scheduledTrial.trialTask());
                }
              }, MoreExecutors.directExecutor());
      pendingTrials.add(current);
      // ignore failure of the prior task.
      previous = Futures.catchingAsync(current, Throwable.class, FALLBACK_TO_NULL, MoreExecutors.directExecutor());
    }
    return pendingTrials;
  }

  /** Returns all the ScheduledTrials for this run. */
  private List<ScheduledTrial> createScheduledTrials(ImmutableSet<Experiment> experimentsToRun,
      int totalTrials) {
    List<ScheduledTrial> trials = Lists.newArrayListWithCapacity(totalTrials);
    /** This is 1-indexed because it's only used for display to users.  E.g. "Trial 1 of 27" */
    int trialNumber = 1;
    for (int i = 0; i < options.trialsPerScenario(); i++) {
      for (Experiment experiment : experimentsToRun) {
        try {
          TrialScopeComponent trialScopeComponent = mainComponent.newTrialComponent(
              new TrialModule(UUID.randomUUID(), trialNumber, experiment));

          trials.add(trialScopeComponent.getScheduledTrial());
        } finally {
          trialNumber++;
        }
      }
    }
    return trials;
  }

  /**
   * Attempts to run each given scenario once, in the current VM. Returns a set of all of the
   * scenarios that didn't throw a {@link SkipThisScenarioException}.
   */
  ImmutableSet<Experiment> dryRun(Iterable<Experiment> experiments)
      throws InvalidBenchmarkException {
    ImmutableSet.Builder<Experiment> builder = ImmutableSet.builder();
    for (Experiment experiment : experiments) {
      try {
        ExperimentComponent experimentComponent =
            mainComponent.newExperimentComponent(ExperimentModule.forExperiment(experiment));
        Object benchmark = experimentComponent.getBenchmarkInstance();
        benchmarkClass.setUpBenchmark(benchmark);
        try {
          experiment.instrumentation().dryRun(benchmark);
          builder.add(experiment);
        } finally {
          // discard 'benchmark' now; the worker will have to instantiate its own anyway
          benchmarkClass.cleanup(benchmark);
        }
      } catch (SkipThisScenarioException innocuous) {}
    }
    return builder.build();
  }

  public static <T> ImmutableList<ListenableFuture<T>> inCompletionOrder(
      Iterable<? extends ListenableFuture<? extends T>> futures) {
    final ConcurrentLinkedQueue<SettableFuture<T>> delegates = Queues.newConcurrentLinkedQueue();
    ImmutableList.Builder<ListenableFuture<T>> listBuilder = ImmutableList.builder();
    for (final ListenableFuture<? extends T> future : futures) {
      SettableFuture<T> delegate = SettableFuture.create();
      // Must make sure to add the delegate to the queue first in case the future is already done
      delegates.add(delegate);
      future.addListener(new Runnable() {
        @Override public void run() {
          SettableFuture<T> delegate = delegates.remove();
          try {
            delegate.set(Uninterruptibles.getUninterruptibly(future));
          } catch (ExecutionException e) {
            delegate.setException(e.getCause());
          } catch (CancellationException e) {
            delegate.cancel(true);
          }
        }
      }, MoreExecutors.directExecutor());
      listBuilder.add(delegate);
    }
    return listBuilder.build();
  }
}