Statistics调用
Statistics stats = Statistics.newInstance(“SiteMonitorController.getSiteMonitorTotal”);
//1-step-节点
stats.mark();
}finally{
//5-step最后一定要加end,大于此毫秒数,才记录日志,否则不记录
stats.end(200);
}
Statistics类实现:
package com.sunlands.eagle.common;
import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- 分步耗时,性能统计
- @author guangchao
*/
public class Statistics {
private static final Logger logger = LoggerFactory.getLogger("Statistics");
private String name;
public void setName(String name) {
this.name = name;
}
public static Statistics newInstance(){
return new Statistics();
}
public static Statistics newInstance(String name){
return new Statistics(name);
}
private List<Long> timeCostList = null;
private Statistics(){
timeCostList = new LinkedList<Long>();
timeCostList.add(System.currentTimeMillis());
}
private Statistics(String name){
this.name = name;
timeCostList = new LinkedList<Long>();
timeCostList.add(System.currentTimeMillis());
}
public void mark(){
timeCostList.add(System.currentTimeMillis());
}
public void end(){
timeCostList.add(System.currentTimeMillis());
StringBuilder timeBuilder = new StringBuilder();
if(name!=null){
timeBuilder.append("[["+name+"]] ");
}
int size = timeCostList.size();
int step = 0;
for(int i=1; i<size; i++){//从1开始
timeBuilder.append(++step).append(":").append(timeCostList.get(i)-timeCostList.get(i-1)).append(" ");
}
logger.info(timeBuilder.toString());
}
/**
* 大于debug的才记录日志,单位(ms)
* @param debug
*/
public void end(long debug){
Long first = timeCostList.get(0);
Long last = System.currentTimeMillis();
if((last-first)>=debug){
end();
}
}
public static void main(String[] args) throws InterruptedException {
Statistics stat = Statistics.newInstance();
Thread.sleep(50);
//1 step
stat.mark();
Thread.sleep(100);
//2 step
stat.mark();
Thread.sleep(200);
//3 step
stat.end(100);
}
}