在流计算、数据传输之类的系统中,有时候需要统计、压测下一下系统的吞吐能力,这里写了一段简单实现记录一下,方便以后使用,构造参数有两个,一个是name,用于区分,一个是采样周期。
发送或者接收代码中调用update方法即可
public class ThroughputProbe extends TimerTask {
private static Logger log = Logger.getLogger(ThroughputProbe.class);
private long count = 0;
private int sampleCount = 0;
private long samplingRateInSeconds;
private String name;
private double maxThroughput = 0.0;
private double minThroughput = Double.MAX_VALUE;
private double accumulatedThroughput = 0.0;
DecimalFormat formatter = new DecimalFormat("#.000");
Timer timer;
private long totalEventCount = 0;
public ThroughputProbe(String name, int samplingRateInSeconds){
this.name = name;
this.samplingRateInSeconds = samplingRateInSeconds;
}
public void startSampling(){
count = 0l;
timer = new Timer();
timer.schedule(this, samplingRateInSeconds * 1000, samplingRateInSeconds * 1000);
}
public void update(){
count++;
totalEventCount++;
}
@Override
public void run() {
if (log.isDebugEnabled()){
if (totalEventCount > 0){
double throughput = count / samplingRateInSeconds;
if (maxThroughput < throughput){
maxThroughput = throughput;
}
if (minThroughput > throughput && throughput != 0.0){
minThroughput = throughput;
}
accumulatedThroughput += throughput;
sampleCount++;
log.debug("[ThroughputProbe:" + name + "] " + count + " events in " + samplingRateInSeconds
+ " seconds. Throughput=" + formatter.format(throughput)
+ " events/s.(Avg=" + formatter.format(accumulatedThroughput / sampleCount)
+ " ,Max=" + formatter.format(maxThroughput)
+ " ,Min=" + ((minThroughput == Double.MAX_VALUE) ? "0.0" : formatter.format(minThroughput))
+ " ) TotalEvents=" + totalEventCount);
count = 0l;
}
}
}
}