KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > fjank > tests > CompareWithHashMap


1 /* Open Source Java Caching Service
2  * Copyright (C) 2002 Frank Karlstrøm
3  * This library is free software; you can redistribute it and/or
4  * modify it under the terms of the GNU Lesser General Public
5  * License as published by the Free Software Foundation; either
6  * version 2.1 of the License, or (at your option) any later version.
7  *
8  * This library is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  * Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public
14  * License along with this library; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16  *
17  * The author can be contacted by email: fjankk@users.sourceforge.net
18  */

19 package org.fjank.tests;
20
21 import java.io.BufferedWriter JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileWriter JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.lang.reflect.Method JavaDoc;
26 import java.text.DateFormat JavaDoc;
27 import java.text.DecimalFormat JavaDoc;
28 import java.text.NumberFormat JavaDoc;
29 import java.util.Collection JavaDoc;
30 import java.util.Date JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Map JavaDoc;
34 import javax.util.jcache.Cache;
35 import javax.util.jcache.CacheAccessFactory;
36 import javax.util.jcache.CacheAttributes;
37 import javax.util.jcache.CacheException;
38 import javax.util.jcache.CacheNotAvailableException;
39
40 /**
41  * Compares the performance of hashmap with FKache.
42  *
43  * @author Frank Karlstrøm
44  */

45 public class CompareWithHashMap {
46     private NumberFormat JavaDoc countFormat = new DecimalFormat JavaDoc("###,###");
47     private int testTime = 1000;
48     private File JavaDoc file;
49     private Map JavaDoc results;
50     private Map JavaDoc jcache;
51     private Map JavaDoc other;
52     
53
54     public CompareWithHashMap(File JavaDoc file) {
55         this.file = file;
56         
57         
58         
59     }
60
61     public static void main(String JavaDoc[] args) {
62         if (args == null) {
63             System.out.println("Missing required argument outputdir.");
64             System.exit(0);
65         }
66         if (args.length == 0) {
67             System.out.println("Missing required argument outputdir.");
68             System.exit(0);
69         }
70         String JavaDoc dir = args[0];
71         File JavaDoc file = new File JavaDoc(dir,"performance.xml");
72         CompareWithHashMap comp = new CompareWithHashMap(file);
73         comp.executeTest();
74         comp.writeResults();
75     }
76
77     private void writeResults() {
78         try {
79             BufferedWriter JavaDoc writer = new BufferedWriter JavaDoc(new FileWriter JavaDoc(file));
80             StringBuffer JavaDoc res = new StringBuffer JavaDoc("<document>\n" + "<properties>\n" + "<title>Performance comparison with HashMap</title>\n" + "</properties>\n"
81                     + "<body>" +
82                             "<section name=\"Test harness\"><p>All tests will be successfull " +
83                             "50% of the time, the other 50% will not be successfull, since the" +
84                             "Maps is pre-initialized for each test with keys/values 0-500, and the tests are runned with" +
85                             "keys/values 0-1000." +
86                             "The keys are Strings, while the values are integers.</p></section>" +
87                             "<section name=\"Performance metrics\">\n"
88                     + "<p>This page presents the results of executing a performance test of FKache versus java.util.HashMap.\n");
89             res.append("The tests was performed on "+ DateFormat.getDateTimeInstance().format(new Date JavaDoc())+".\n");
90             res.append("The tests was runned on "+System.getProperty("java.runtime.name") +
91                     " version " + System.getProperty("java.vm.version") +
92                     " by " + System.getProperty("java.vm.vendor")+".\n");
93             res.append("The operating system was "+ System.getProperty("os.name")+".\n");
94             res.append("The amount of available memory to the VM was " + Runtime.getRuntime().maxMemory()/1024/1024 + "Mb.\n");
95             if(!results.isEmpty()) {
96                 res.append("<table><tr><th>method</th><th>Number of repeats</th><th>HashMap</th><th>FKache</th></tr>\n");
97                 Iterator JavaDoc iter = results.keySet().iterator();
98                 while(iter.hasNext()) {
99                     String JavaDoc method = (String JavaDoc) iter.next();
100                     float[] fs = (float[]) results.get(method);
101                     res.append("<tr><td>"+method+"</td><td>"+countFormat.format((long)fs[0]*1000)+"</td><td>"+100*fs[1]+"%</td><td>"+(long)(100F*fs[2])+"%</td></tr>\n");
102                 }
103                 res.append("</table>");
104             }
105             res.append("</p>\n</section>\n</body>\n</document>");
106             writer.write(res.toString());
107             writer.close();
108         } catch (IOException JavaDoc e) {
109             e.printStackTrace();
110             throw new IllegalStateException JavaDoc("The results could not be written.");
111         }
112     }
113
114     private void executeTest() {
115         
116         Map JavaDoc val = new HashMap JavaDoc();
117         Method JavaDoc[] methods = Map JavaDoc.class.getDeclaredMethods();
118         for (int i = 0; i < methods.length; i++) {
119             Method JavaDoc method = methods[i];
120             if(method.getName().equals("hashCode") || method.getName().equals("equals")) {
121                 continue;
122             }
123             Class JavaDoc[] types = method.getParameterTypes();
124             String JavaDoc params = "(";
125             for (int j = 0; j < types.length; j++) {
126                 String JavaDoc name = types[j].getName();
127                 if(name.indexOf(".")!=-1) {
128                     name=name.substring(name.lastIndexOf(".")+1);
129                 }
130                 params+=name;
131                 if(j!=types.length-1) {
132                     params+=", ";
133                 }
134             }
135             params+=")";
136             
137             val.put(method.getName()+params, execute(method));
138         }
139
140         this.results = val;
141     }
142     
143     
144
145     private float[] execute(Method JavaDoc meth) {
146         long otherTime = 0;
147         long fkacheTime = 0;
148         initOther();
149         initJCacheMap();
150         prepare(other);
151         prepare(jcache);
152         int reps=1;
153         while((otherTime = repeat(other,meth, reps))<testTime) {
154             if(otherTime==0) {
155                 otherTime++;
156             }
157             long factor = testTime/otherTime;
158             if(factor<=0) {
159                 factor+=2;
160             }else if(factor==1) {
161                 factor++;
162             }
163             System.out.println("increasing with "+factor+" to "+(reps*=factor) + " for "+meth.getName()+", took:" + otherTime);
164         }
165         //ok...
166
otherTime=repeat(other,meth, reps);
167         System.out.println("finished HashMap");
168         fkacheTime=repeat(jcache,meth, reps);
169         System.out.println("other:"+otherTime+", FKache:"+fkacheTime);
170         return new float[] {reps, 1,((float)fkacheTime/(float)otherTime)};
171     }
172
173     private void prepare(Map JavaDoc map) {
174         for(int i=0; i<500; i++) {
175             map.put(""+i, new Integer JavaDoc(i));
176         }
177     }
178
179     private long repeat(Map JavaDoc map, Method JavaDoc method, int reps) {
180         try {
181             Object JavaDoc obj=null;
182             boolean b=false;
183             int size=0;
184             Collection JavaDoc values=null;
185             long time = System.currentTimeMillis();
186             if (method.getName().equals("isEmpty")) {
187                 for (int y = 0; y < reps; y++) {
188                     for (int i = 999; i >= 0; i--) {
189                         b=map.isEmpty();
190                     }
191                 }
192             } else if (method.getName().equals("size")) {
193                 for (int y = 0; y < reps; y++) {
194                     for (int i = 999; i >= 0; i--) {
195                         size=map.size();
196                     }
197                 }
198             } else if (method.getName().equals("hashCode")) {
199                 for (int y = 0; y < reps; y++) {
200                     for (int i = 999; i >= 0; i--) {
201                         size = map.hashCode();
202                     }
203                 }
204             } else if (method.getName().equals("containsValue")) {
205                 Object JavaDoc[][] params = prepareParams(method);
206                 
207                 for (int y = 0; y < reps; y++) {
208                     for (int i = 999; i >= 0; i--) {
209                         b=map.containsValue(params[i][0]);
210                     }
211                 }
212             } else if (method.getName().equals("containsKey")) {
213                 Object JavaDoc[][] params = prepareParams(method);
214                 
215                 for (int y = 0; y < reps; y++) {
216                     for (int i = 999; i >= 0; i--) {
217                         b=map.containsKey(params[i][0]);
218                     }
219                 }
220             } else if (method.getName().equals("get")) {
221                 Object JavaDoc[][] params = prepareParams(method);
222                 
223                 for (int y = 0; y < reps; y++) {
224                     for (int i = 999; i >= 0; i--) {
225                         obj=map.get(params[i][0]);
226                     }
227                 }
228             } else if (method.getName().equals("values")) {
229                 
230                 for (int y = 0; y < reps; y++) {
231                     for (int i = 999; i >= 0; i--) {
232                         values = map.values();
233                     }
234                 }
235             } else if (method.getName().equals("equals")) {
236                 Object JavaDoc[][] params = prepareParams(method);
237                 
238                 for (int y = 0; y < reps; y++) {
239                     for (int i = 999; i >= 0; i--) {
240                         b = map.equals(params[i][0]);
241                     }
242                 }
243             } else if (method.getName().equals("entrySet")) {
244                 for (int y = 0; y < reps; y++) {
245                     for (int i = 999; i >= 0; i--) {
246                         values = map.entrySet();
247                     }
248                 }
249             } else if (method.getName().equals("clear")) {
250                 for (int y = 0; y < reps; y++) {
251                     for (int i = 999; i >= 0; i--) {
252                         map.clear();
253                     }
254                 }
255             } else if (method.getName().equals("putAll")) {
256                 for (int y = 0; y < reps; y++) {
257                     for (int i = 999; i >= 0; i--) {
258                         map.putAll(testMap);
259                     }
260                 }
261             } else if (method.getName().equals("remove")) {
262                 Object JavaDoc[][] params = prepareParams(method);
263                 
264                 for (int y = 0; y < reps; y++) {
265                     for (int i = 999; i >= 0; i--) {
266                         obj = map.remove(params[i][0]);
267                     }
268                 }
269             } else if (method.getName().equals("put")) {
270                 Object JavaDoc[][] params = prepareParams(method);
271                 
272                 for (int y = 0; y < reps; y++) {
273                     for (int i = 999; i >= 0; i--) {
274                         obj = map.put(params[i][0], params[i][1]);
275                     }
276                 }
277             } else if (method.getName().equals("keySet")) {
278                 for (int y = 0; y < reps; y++) {
279                     for (int i = 999; i >= 0; i--) {
280                         values = map.keySet();
281                     }
282                 }
283             }
284             long took = System.currentTimeMillis() - time + 1;
285             if (obj != null && b && size==0 && values!=null) {
286                 obj.toString();
287             }
288             return took;
289         } catch (Exception JavaDoc e) {
290             IllegalStateException JavaDoc ie = new IllegalStateException JavaDoc(method.toString());
291             ie.initCause(e);
292             throw ie;
293         }
294     }
295
296     private Object JavaDoc[][] prepareParams(Method JavaDoc method) throws InstantiationException JavaDoc, IllegalAccessException JavaDoc {
297         Class JavaDoc[] types = method.getParameterTypes();
298         Object JavaDoc[][] params = new Object JavaDoc[1000][types.length];
299         Map JavaDoc testMap = getTestMap();
300         for(int i=0; i<1000; i++) {
301             for (int j = 0; j < types.length; j++) {
302                 Class JavaDoc type = types[j];
303                 if(type==Map JavaDoc.class) {
304                     params[i][j]=testMap;
305                 }
306                 if(j==0) {
307                     if(type==Object JavaDoc.class){
308                         params[i][0]=Integer.toString(i);
309                     }else if(params[0]==null) {
310                         params[i][0]=type.newInstance();
311                     }
312                 }else if (j==1) {
313                     if(type==Object JavaDoc.class){
314                         params[i][1]=new Integer JavaDoc(i);
315                     }else if(params[1]==null){
316                         params[i][1]=type.newInstance();
317                     }
318                 }
319             }
320         }
321         return params;
322     }
323     private Map JavaDoc testMap = new HashMap JavaDoc();
324     private Map JavaDoc getTestMap() {
325        if(testMap.isEmpty()) {
326             for(int i=0; i<1000; i++) {
327                 testMap.put(""+i, new Integer JavaDoc(i));
328             }
329        }
330         return testMap;
331     }
332
333     private void initJCacheMap() {
334         try {
335             CacheAccessFactory factory = CacheAccessFactory.getInstance();
336             Cache cache = factory.getCache(false);
337             CacheAttributes attributes = CacheAttributes.getDefaultCacheAttributes();
338             attributes.setLocal();
339             attributes.setMaxObjects(100000000);
340             cache.init(attributes);
341             this.jcache= factory.getMapAccess();
342         } catch (CacheNotAvailableException e) {
343             throw new IllegalStateException JavaDoc(e.getMessage());
344         } catch (CacheException e) {
345             throw new IllegalStateException JavaDoc(e.getMessage());
346         }
347     }
348
349     private void initOther() {
350         this.other=new HashMap JavaDoc();
351     }
352 }
Popular Tags