1 package tests.jfun.parsec; 2 3 import junit.framework.TestCase; 4 5 11 public class LoopBenchmark extends TestCase{ 12 public class State{ 13 private boolean ok; 14 State(){ 15 this.ok = false; 16 } 17 void setOk(boolean ok){ 18 this.ok = ok; 19 } 20 boolean isOk(){ 21 return ok; 22 } 23 } 24 interface Factory{ 25 Object create(State state); 26 } 27 class FailedFactory implements Factory{ 28 public Object create(State state){ 29 state.setOk(false); 30 return null; 31 } 32 } 33 static final int times = 10000000; 34 public void test1(){ 35 final Factory factory = new FailedFactory(); 36 final State state = new State(); 37 benchmarkFactory(factory, state); 38 benchmarkException(new ErrorFactory(), state); 39 benchmarkException(new ThrowingFactory(), state); 40 } 41 42 private void benchmarkFactory(Factory factory, State state){ 43 final long startTime = System.currentTimeMillis(); 44 for(int i=0; i<times; i++){ 45 factory.create(state); 46 if(state.isOk()) 47 break; 48 } 49 final long endTime = System.currentTimeMillis(); 50 System.out.println(endTime-startTime); 51 } 52 53 private static final RuntimeException ex = new RuntimeException (); 54 class ErrorFactory implements Factory{ 55 public Object create(State state){ 56 throw ex; 57 } 58 } 59 60 class ThrowingFactory implements Factory{ 61 public Object create(State state){ 62 throw new RuntimeException (); 63 } 64 } 65 private void benchmarkException(Factory factory, State state){ 66 final long startTime = System.currentTimeMillis(); 67 for(int i=0; i<times; i++){ 68 try{ 69 factory.create(state); 70 } 71 catch(RuntimeException e){continue;} 72 break; 73 } 74 final long endTime = System.currentTimeMillis(); 75 System.out.println(endTime-startTime); 76 } 77 } 78 | Popular Tags |