KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > memory > MeasureBaselineMemoryFootprint


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package memory;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileReader JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.io.LineNumberReader JavaDoc;
28
29 import java.util.StringTokenizer JavaDoc;
30
31 /**
32  * Measure memory footprint, by checking size of memory occupied by runide process.
33  * On Windows platform used <b>pslist.exe</b>, on Unix platform used <b>ps</b>.
34  * Output of these commands is parsed and measured memory size
35  * (windows - "MEM", unix - "RES", "RSS") presents as measured memory footprint.
36  *
37  * @author mmirilovic@netbeans.org
38  */

39 public class MeasureBaselineMemoryFootprint extends org.netbeans.junit.NbPerformanceTestCase{
40     
41     /** Used platform. */
42     private static String JavaDoc platform;
43     
44     /** IDE process PID. */
45     private static long pid;
46     
47     /** Ouput file where is logged ouput from ps command. */
48     private static String JavaDoc PS_OUTPUT_FILENAME = "psOutput.txt";
49     
50     private static final String JavaDoc UNIX = "unix";
51     private static final String JavaDoc WINDOWS = "windows";
52     private static final String JavaDoc UNKNOWN = "unknown";
53     
54     private static final String JavaDoc [][] SUPPORTED_PLATFORMS = {
55         {"Linux,i386",UNIX},
56         {"SunOS,sparc",UNIX},
57         {"Windows_NT,x86",WINDOWS},
58         {"Windows_2000,x86",WINDOWS},
59         {"Windows_XP,x86",WINDOWS},
60         {"Windows_95,x86",WINDOWS},
61         {"Windows_98,x86",WINDOWS},
62         {"Windows_Me,x86",WINDOWS}
63     };
64     
65     /** Define testcase
66      * @param testName name of the testcase
67      */

68     public MeasureBaselineMemoryFootprint(String JavaDoc testName) {
69         super(testName);
70     }
71     
72     /** Measure baseline memory footprint */
73     public void testMemoryFootprintAfterStart(){
74         long memory;
75         try {
76             memory = getMemoryConsumption();
77             
78             if(memory>0){
79                 reportPerformance("Memory Consumption After Start", memory , "kB", 1);
80             }else
81                 fail("Measured value = "+memory+"kB - it's wrong value!");
82             
83         }catch(Exception JavaDoc exc){
84             exc.printStackTrace(getLog());
85             fail("Exception rises during measurement : "+exc.toString());
86         }
87     }
88     
89     
90     /**
91      * Measure memory footprint. Looks for file [xtest.tmpdir]/ide.pid
92      * to IDE process PID which is used by utils to measure memory.
93      * @throws IOException if [xtest.tmpdir]/ide.pid file doesn't exist
94      * @return return measured memory footprint
95      */

96     private long getMemoryConsumption() throws IOException JavaDoc {
97         String JavaDoc workdir = System.getProperty("xtest.tmpdir");
98         
99         File JavaDoc ideRunning;
100         log("Start");
101         
102         if (workdir!=null) {
103             log("Workdir {"+workdir+"}.");
104             workdir = workdir.substring(0,workdir.lastIndexOf(File.separator));
105             
106             // create flag file indicating running tests
107
ideRunning = new File JavaDoc(workdir,"ide.pid");
108             log("Looking for file {"+ideRunning.getAbsolutePath()+"}.");
109             
110             if (ideRunning.exists()) {
111                 log("PID file exists.");
112                 try {
113                     LineNumberReader JavaDoc reader = new LineNumberReader JavaDoc(new FileReader JavaDoc(ideRunning));
114                     String JavaDoc line = reader.readLine();
115                     if (line != null) {
116                         try {
117                             pid = Long.parseLong(line);
118                             log("Measure memory footprint of process with PID="+pid);
119                             long measuredMemory = measureMemory();
120                             Thread.sleep(2000);
121                             return measuredMemory;
122                         } catch (NumberFormatException JavaDoc nfe) {
123                             nfe.printStackTrace(getLog());
124                             fail("Cannot parse PID written in the ide.pid file: "+line+"- cannot measure.");
125                         }
126                     }
127                 } catch (IOException JavaDoc ioe) {
128                     ioe.printStackTrace(getLog());
129                     fail("IOException when reading PID from ide.pid file - cannot measure");
130                 } catch (Exception JavaDoc e) {
131                     e.printStackTrace(getLog());
132                     fail("Exception when trying to measure IDE's used memory");
133                 }
134             } else {
135                 fail("Cannot find file containing PID of running IDE ("+ideRunning.getAbsolutePath()+") - cannot measure");
136             }
137         } else {
138             fail("xtest.workdir property is not specified - cannot measure");
139         }
140         fail("Wrong state");
141         return 0;
142     }
143     
144     
145     /**
146      * Run appropriate command against used platform.
147      * @return return measured memory footprint
148      */

149     private long measureMemory(){
150         platform = getPlatform();
151         
152         log("Platform="+platform);
153         
154         if (platform.equals(UNIX))
155             return psOnUnix();
156         else if (platform.equals(WINDOWS))
157             return psOnWindows();
158         else
159             fail("Unsupported platform!");
160         
161         return 0;
162     }
163     
164     /**
165      * Execute appropriate command and save output as file psOutput.txt.
166      * @param psCommand command to be runned (using platform dependent util)
167      */

168     private void executePsCommand(String JavaDoc psCommand){
169         log("Ecexute command: ["+psCommand+"].");
170         
171         try {
172             Process JavaDoc ps = Runtime.getRuntime().exec(psCommand);
173             
174             StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
175             BufferedReader JavaDoc dataInput = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(ps.getInputStream()));
176             String JavaDoc line;
177             
178             while ((line = dataInput.readLine()) != null) {
179                 buffer.append(line);
180                 buffer.append('\n');
181             }
182             
183             getLog(PS_OUTPUT_FILENAME).print(buffer.toString());
184             ps.waitFor();
185             
186             log("ps command exit value = "+ps.exitValue());
187         } catch (InterruptedException JavaDoc ie) {
188             ie.printStackTrace(getLog());
189             log("InterruptedException when ps :"+ie.toString());
190         } catch (IOException JavaDoc ioe){
191             ioe.printStackTrace(getLog());
192             log("None output from command ps, exception arise "+ioe.toString());
193         }
194     }
195     
196     
197     /**
198      * Execute commands :
199      * <pre>
200      * ps -A -o pid,comm,rss
201      * </pre>
202      * and save output as file psOutput.txt.
203      * @param psCommand command to be runned (using platform depend util)
204      */

205     private long psOnUnix(){
206         long returnValue = 0;
207   
208         executePsCommand("ps -A -o pid,comm,rss");
209         returnValue = parsePsFile();
210         
211         return returnValue;
212     }
213     
214     /**
215      * Execute commands :
216      * <pre>
217      * pslist.exe
218      * </pre>
219      * and save output as file psOutput.txt.
220      * @param psCommand command to be runned (using platform depend util)
221      */

222     private long psOnWindows(){
223         String JavaDoc xtestHome = System.getProperty("xtest.tmpdir");
224         if (xtestHome != null) {
225             File JavaDoc psFile = new File JavaDoc(xtestHome,"pslist.exe");
226             String JavaDoc psPath = psFile.getAbsolutePath();
227             String JavaDoc psCommand = psPath;
228             executePsCommand(psCommand);
229             return parsePsFile();
230         } else {
231             fail("xtest.home system property not set - cannot find ps distributed with XTest on windows");
232         }
233         return 0;
234     }
235     
236     
237     /**
238      * Parse file (created as output from ps command) and looks for line with appropriate pid.
239      * File can be found (if exists) after test run in working directory. If file has not been created
240      * return 0. If work dir doesn't exist or output file exists but line with appropriate PID doens't
241      * exists there -> test fails.
242      * @return measured memory - parsed output from command ps
243      */

244     private long parsePsFile(){
245         String JavaDoc workDirPath = "";
246         
247         try {
248             workDirPath = getWorkDir().getAbsolutePath();
249         }catch(IOException JavaDoc ioe){
250             ioe.printStackTrace(getLog());
251             fail("It isn't possible to get work directory, arise exception :"+ioe.toString());
252         }
253         
254         try {
255             File JavaDoc psOutput = new File JavaDoc(workDirPath, PS_OUTPUT_FILENAME);
256             log("Parse file "+psOutput.getAbsolutePath());
257             
258             BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new FileReader JavaDoc(psOutput));
259             String JavaDoc line;
260             
261             while((line = reader.readLine()) != null){
262                 log("\t Line=["+line+"]");
263                 long memory = getMemory(line);
264                 if(memory!=0)
265                     return memory;
266             }
267             
268 // fail("Cannot find line with PID in output from ps command!");
269

270         } catch(IOException JavaDoc ioe){
271             ioe.printStackTrace(getLog());
272             log("None output from ps command, arise exception :"+ioe.toString());
273         }
274         
275         return 0;
276     }
277     
278     
279     /** Get used memory size parsed from one line of output from command ps .
280      * Transform memory size to [kB]. Type of parser depends on used platform.
281      * @param line line from command ps's output file
282      * @return measured memory
283      */

284     private long getMemory(String JavaDoc line){
285         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(line);
286         String JavaDoc line_pid,line_mem;
287         long memory = 0;
288         long ppid;
289         
290         if(line.length()>0){
291             if (platform.equals(UNIX)) {
292                 line_pid = st.nextToken();
293                 try {
294                     ppid = Long.parseLong(line_pid);
295                 }catch(NumberFormatException JavaDoc exc){
296                     return 0;
297                 }
298                 
299                 log("\t proces pid="+ppid + " looking for pid="+pid);
300                 
301                 if(pid == ppid){
302                     st.nextToken();
303                     line_mem = st.nextToken();
304                     memory = Long.parseLong(line_mem);
305                 }
306                 
307             } else if (platform.equals(WINDOWS)) {
308                 st.nextToken();
309                 line_pid = st.nextToken();
310                 try {
311                     ppid = Long.parseLong(line_pid);
312                 }catch(NumberFormatException JavaDoc exc){
313                     return 0;
314                 }
315                 
316                 log("\t proces pid="+ppid + " looking for pid="+pid);
317                 if(pid == ppid){
318                     for(int i=0;i<3;i++)
319                         st.nextToken();
320                     line_mem = st.nextToken();
321                     
322                     memory = Long.parseLong(line_mem);
323                 }
324             } else {
325                 fail("Unsupported platform!");
326             }
327             
328         }
329         log("Memory="+memory);
330         return memory;
331     }
332     
333     /**
334      * Get platform on which the code is executed.
335      * @return platform identification string
336      */

337     private static String JavaDoc getPlatform() {
338         
339         String JavaDoc platformString=(System.getProperty("os.name","")+","+
340                         /*
341                         System.getProperty("os.version","")+","+
342                          */

343         System.getProperty("os.arch","")).replace(' ','_');
344         for (int i=0; i<SUPPORTED_PLATFORMS.length; i++) {
345             if (platformString.equalsIgnoreCase(SUPPORTED_PLATFORMS[i][0])) {
346                 return SUPPORTED_PLATFORMS[i][1];
347             }
348         }
349         return UNKNOWN;
350     }
351     
352     
353 }
354
Popular Tags