/*
* PerfTemplate.java
*
* Created on October 15, 2007, 11:47 PM
*
*/
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author praveenm
*/
public abstract class PerfTemplate {
// testing
public static void main(String[] args){
for(int a=0;a<10;a++){
new PerfTemplate(){void runIn()throws Exception {
System.out.println("Doing some printing task");
}}.execute("Printing Task :");
}
PerfTemplate.close();
}
private static final String DEFAULT_FILE = "performance";
private static java.io.Writer writer =null;
public PerfTemplate(){
if(writer!=null) return;
try {
File file = new File(DEFAULT_FILE+"_"+dformat.format(new Date())+".csv");
writer = new java.io.FileWriter(file,true);
if(file.length()<1){
writer.write("Task Name,Time Taken,Execution Time,Memory Usage");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static synchronized void setWriter(java.io.Writer writer){
close();
writer=writer;
}
abstract void runIn() throws Exception;
public final static void close(){
if(writer!=null){
try {
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static final SimpleDateFormat tformat = new SimpleDateFormat("H:mm:ss");
private static final SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd");
public final void execute(String taskName){
long start = System.currentTimeMillis();
String msg="0,0,0,0";
Memory mem= new Memory();
mem.start();
String memory="";
try {
runIn();
long end = System.currentTimeMillis();
memory=mem.memorySizeToString(mem.end());
msg = "\n"+taskName+","+(end-start)+","+(tformat.format(new Date())+","+memory);
} catch (Exception ex) {
ex.printStackTrace();
long end = System.currentTimeMillis();
msg = "\n"+taskName+" Exception"+ex+","+(end-start)+","+(tformat.format(new Date()))+memory;
//throw new RuntimeException("Got Exception I Can't profile on \""+taskName+"\" Task");
}
//System.out.println(msg);
try {
if(writer!=null){
writer.write(msg);
writer.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
class Memory {
long usage;
public void start(){
garbageCollect();
Runtime r=Runtime.getRuntime();
usage=r.totalMemory()-r.freeMemory();
}
public long end(){
garbageCollect();
Runtime r=Runtime.getRuntime();
return (r.totalMemory()-r.freeMemory())-usage;
}
public String memorySizeToString(long l){
int MB=(int) (l/1048576);
l=l-1048576*MB;
int KB=(int) (l/1024);
l=l-1024*KB;
return new String(MB+"MB "+KB+"KB "+l+"BYTES");
}
private void garbageCollect() {
Runtime r=Runtime.getRuntime();
r.gc();
r.gc();r.gc();r.gc();
}
}
}