在流計算、數據傳輸之類的系統中,有時候需要統計、壓測下一下系統的吞吐能力,這裏寫了一段簡單實現記錄一下,方便以後使用,構造參數有兩個,一個是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;
}
}
}
}