我写了一个计时器,它将测量任何多线程应用程序中特定代码的性能.在下面的定时器中,它还将填充地图,需要多少个调用x毫秒.我将使用这个地图作为我的直方图的一部分进行进一步的分析,比如说这个毫秒数的等待时间是多少.
public static class StopWatch {
public static ConcurrentHashMap histogram = new ConcurrentHashMap();
/**
* Creates an instance of the timer and starts it running.
*/
public static StopWatch getInstance() {
return new StopWatch();
}
private long m_end = -1;
private long m_interval = -1;
private final long m_start;
private StopWatch() {
m_start = m_interval = currentTime();
}
/**
* Returns in milliseconds the amount of time that has elapsed since the timer was created. If the
* stop
method has been invoked, then this returns instead the elapsed time between the creation of
* the timer and the moment when stop
was invoked.
*
* @return duration it took
*/
public long getDuration() {
long result = 0;
final long startTime = m_start;
final long endTime = isStopWatchRunning() ? currentTime() : m_end;
result = convertNanoToMilliseconds(endTime - startTime);
boolean done = false;
while (!done) {
Long oldValue = histogram.putIfAbsent(result, 1L);
if (oldValue != null) {
done = histogram.replace(result, oldValue, oldValue + 1);
} else {
done = true;
}
}
return result;
}
/**
* Returns in milliseconds the amount of time that has elapsed since the last invocation of this same method. If
* this method has not previously been invoked, then it is the amount of time that has elapsed since the timer
* was created. Note that once the stop
method has been invoked this will just
* return zero.
*
* @return interval period
*/
public long getInterval() {
long result = 0;
final long startTime = m_interval;
final long endTime;
if (isStopWatchRunning()) {
endTime = m_interval = currentTime();
} else {
endTime = m_end;
}
result = convertNanoToMilliseconds(endTime - startTime);
return result;
}
/**
* Stops the timer from advancing. This has an impact on the values returned by both the
* getDuration
and the getInterval
methods.
*/
public void stop() {
if (isStopWatchRunning()) {
m_end = currentTime();
}
}
/**
* What is the current time in nanoseconds?
*
* @return returns back the current time in nanoseconds
*/
private long currentTime() {
return System.nanoTime();
}
/**
* This is used to check whether the timer is alive or not
*
* @return checks whether the timer is running or not
*/
private boolean isStopWatchRunning() {
return (m_end <= 0);
}
/**
* This is used to convert NanoSeconds to Milliseconds
*
* @param nanoseconds
* @return milliseconds value of nanoseconds
*/
private long convertNanoToMilliseconds(final long nanoseconds) {
return nanoseconds / 1000000L;
}
}
例如,这是我将使用我的上述计时器类来衡量我的多线程应用程序中特定代码的性能:
StopWatch timer = StopWatch.getInstance();
//... some code here to measure
timer.getDuration();
现在我的问题是 – 从直方图中计算请求的平均值,中值,第95和第99百分位数的最佳方法是什么?我的意思是说,我想在我的StopWatch类中添加一些方法,它将像所有的计算一样找到平均值,中值,第95和第99百分位数.
然后我可以直接使用StopWatch实例来获取它.
我的直方图应该是这样的:
key – means number of milliseconds
value – means number of calls that took that much milliseconds.