Statistics--统计各环节耗时情况

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);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值