1 /* 2 * Copyright (C) 2017 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 // This test was inspired by benchmarks.MicroMethodHandles.java.MicroMethodHandles. 18 19 import java.io.PrintStream; 20 import java.lang.invoke.MethodHandle; 21 import java.lang.invoke.MethodHandles; 22 import java.lang.invoke.MethodType; 23 24 class A { binaryFunction(int x, double y)25 public Long binaryFunction(int x, double y) { 26 return 1000l; 27 } 28 } 29 30 class Test { Test()31 Test() throws Throwable { 32 this.handle = MethodHandles.lookup().findVirtual(A.class, "binaryFunction", 33 MethodType.methodType(Long.class, int.class, 34 double.class)); 35 this.a = new A(); 36 this.x = new Integer(72); 37 this.y = new Double(-1.39e-31); 38 } 39 execute()40 void execute() { 41 try { 42 executeFor(2000); 43 System.out.println(getName()); 44 } catch (Throwable t) { 45 System.err.println("Exception during the execution of " + getName()); 46 System.err.println(t); 47 t.printStackTrace(new PrintStream(System.err)); 48 System.exit(1); 49 } 50 } 51 executeFor(long timeMinimumMillis)52 void executeFor(long timeMinimumMillis) throws Throwable { 53 long startTime = System.currentTimeMillis(); 54 long elapsed = 0; 55 while (elapsed < timeMinimumMillis) { 56 exercise(); 57 elapsed = System.currentTimeMillis() - startTime; 58 } 59 } 60 exercise()61 void exercise() throws Throwable { 62 for (int i = 0; i < EXERCISE_ITERATIONS; ++i) { 63 run(); 64 } 65 } 66 run()67 void run() throws Throwable { 68 long result = (long) handle.invoke(a, x, y); 69 } 70 getName()71 String getName() { 72 return getClass().getSimpleName(); 73 } 74 75 private static final int EXERCISE_ITERATIONS = 500; 76 77 private MethodHandle handle; 78 private A a; 79 private Integer x; 80 private Double y; 81 } 82 83 public class Main { main(String[] args)84 public static void main(String[] args) throws Throwable { 85 Test[] tests = new Test[] { new Test(), new Test(), new Test() }; 86 for (Test test : tests) { 87 test.execute(); 88 } 89 System.out.println("passed"); 90 } 91 } 92