1 2 public class Main { 3 static class SuperClass { getVar(int w)4 protected static int getVar(int w) { 5 return w & 0xF; 6 } 7 } 8 static class SubClass extends SuperClass { getVarDirect(int w)9 final int getVarDirect(int w) { 10 return w & 0xF; 11 } testDirect(int max)12 public void testDirect(int max) { 13 for (int i = 0; i < max; ++i) { 14 getVarDirect(max); 15 } 16 } testStatic(int max)17 public void testStatic(int max) { 18 for (int i = 0; i < max; ++i) { 19 getVar(max); 20 } 21 } 22 } 23 main(String[] args)24 static public void main(String[] args) throws Exception { 25 boolean timing = (args.length >= 1) && args[0].equals("--timing"); 26 run(timing); 27 } 28 testBasis(int interations)29 static int testBasis(int interations) { 30 (new SubClass()).testDirect(interations); 31 return interations; 32 } 33 testStatic(int interations)34 static int testStatic(int interations) { 35 (new SubClass()).testStatic(interations); 36 return interations; 37 } 38 run(boolean timing)39 static public void run(boolean timing) { 40 long time0 = System.nanoTime(); 41 int count1 = testBasis(50000000); 42 long time1 = System.nanoTime(); 43 int count2 = testStatic(50000000); 44 long time2 = System.nanoTime(); 45 46 System.out.println("basis: performed " + count1 + " iterations"); 47 System.out.println("test1: performed " + count2 + " iterations"); 48 49 double basisMsec = (time1 - time0) / (double) count1 / 1000000; 50 double msec1 = (time2 - time1) / (double) count2 / 1000000; 51 52 if (msec1 < basisMsec * 5) { 53 System.out.println("Timing is acceptable."); 54 } else { 55 System.out.println("Iterations are taking too long!"); 56 timing = true; 57 } 58 if (timing) { 59 System.out.printf("basis time: %.3g msec\n", basisMsec); 60 System.out.printf("test1: %.3g msec per iteration\n", msec1); 61 } 62 } 63 } 64