KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > tests > jfun > parsec > LoopBenchmark


1 package tests.jfun.parsec;
2
3 import junit.framework.TestCase;
4
5 /**
6  *
7  * <p>
8  * @author Ben Yu
9  * Apr 10, 2006 9:12:06 PM
10  */

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 JavaDoc create(State state);
26   }
27   class FailedFactory implements Factory{
28     public Object JavaDoc 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 JavaDoc ex = new RuntimeException JavaDoc();
54   class ErrorFactory implements Factory{
55     public Object JavaDoc create(State state){
56       throw ex;
57     }
58   }
59
60   class ThrowingFactory implements Factory{
61     public Object JavaDoc create(State state){
62       throw new RuntimeException JavaDoc();
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 JavaDoc e){continue;}
72       break;
73     }
74     final long endTime = System.currentTimeMillis();
75     System.out.println(endTime-startTime);
76   }
77 }
78
Popular Tags