1 /* 2 * Copyright (C) 2014 The Android Open Source Project 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 public class BenchmarkBase { 18 public final String name; 19 20 // Empty constructor. BenchmarkBase(String name)21 public BenchmarkBase(String name) { 22 this.name = name; 23 } 24 25 // The benchmark code. 26 // This function is not used, if both [warmup] and [exercise] are overwritten. run()27 public void run() throws Throwable { } 28 29 // Runs a short version of the benchmark. By default invokes [run] once. warmup()30 public void warmup() throws Throwable { 31 run(); 32 } 33 34 // Exercises the benchmark. By default invokes [run] 10 times. exercise()35 public void exercise() throws Throwable { 36 for (int i = 0; i < 10; ++i) { 37 run(); 38 } 39 } 40 41 // Not measured setup code executed prior to the benchmark runs. setup()42 public void setup() throws Throwable { } 43 44 // Not measures teardown code executed after the benchark runs. teardown()45 public void teardown() throws Throwable { } 46 47 // Measures the score for this benchmark by executing it repeatedly until 48 // time minimum has been reached. measureFor(boolean doWarmup, long timeMinimum)49 protected double measureFor(boolean doWarmup, long timeMinimum) throws Throwable { 50 int iter = 0; 51 long startTime = System.currentTimeMillis(); 52 long elapsed = 0; 53 while (elapsed < timeMinimum) { 54 if (doWarmup) { 55 warmup(); 56 } else { 57 exercise(); 58 } 59 elapsed = System.currentTimeMillis() - startTime; 60 iter++; 61 } 62 return 1000.0 * elapsed / iter; 63 } 64 65 // Measures the score for the benchmark and returns it. measure()66 public double measure() throws Throwable { 67 setup(); 68 // Warmup for at least 100ms. Discard result. 69 measureFor(true, 100); 70 // Run the benchmark for at least 1000ms. 71 double result = measureFor(false, 1000); 72 teardown(); 73 return result; 74 } 75 76 // Allow subclasses to override how the name is printed. getName()77 public String getName() { 78 return name; 79 } 80 report()81 public void report() throws Throwable { 82 double score = measure(); 83 System.out.println(getName() + "(RunTime): " + score + " us."); 84 } 85 }