Open 122006 opened 7 years ago
@122006 好的,我抽空改一下
@122006 hi 方便加一下微信吗?我想跟你探讨一下这块如何优化比较好。 我的微信号:fengzhizi715
@Around("methodAnnotatedWithTrace() || constructorAnnotatedTrace()") public Object traceMethod(final ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String className = methodSignature.getDeclaringType().getSimpleName(); String methodName = methodSignature.getName(); final StopWatch2 stopWatch = new StopWatch2(); stopWatch.start(); Object result = joinPoint.proceed(); stopWatch.stop();
if (Preconditions.isBlank(className)) {
className = "Anonymous class";
}
mLog.i(buildLogMessage(methodName, stopWatch.getTotalTimeMillis()));
return result;
}
private static final int ns=1000*1000;
/**
* Create a log message.
*
* @param methodName A string with the method name.
* @param methodDuration Duration of the method in milliseconds.
* @return A string representing message.
*/
private static String buildLogMessage(String methodName, long methodDuration) {
if (methodDuration>10*ns){
return String.format("%s() take %d ms", methodName,methodDuration/ns);
}else if (methodDuration>ns){
return String.format("%s() take %dms %dμs", methodName,methodDuration/ns,methodDuration%ns);
}else{
return String.format("%s() take %dμs", methodName,methodDuration%ns);
}
}
public class StopWatch2 { private long startTime; private long endTime; private long elapsedTime;
public StopWatch2() {
}
private void reset() {
startTime = 0;
endTime = 0;
elapsedTime = 0;
}
public void start() {
reset();
startTime = System.nanoTime();
}
public void stop() {
if (startTime != 0) {
endTime = System.nanoTime();
elapsedTime = endTime - startTime;
} else {
reset();
}
}
public long getTotalTimeMillis() {
return (elapsedTime != 0) ? endTime - startTime: 0;
}
}
StopWatch
中的getTotalTimeMillis()可以考虑去掉ms单位转换,直接用微毫秒显示(或者XXmsXXμs) 毕竟大部分时候方法都是0ms但是大量次数运行也有优化的空间