您的位置:首页 > 编程语言

利用StopWatch来监视代码执行效率

2018-01-04 14:53 323 查看
在利用springframework开发的系统中,可以很方便的利用StopWatch工具类来查看每段代码的运行时间,以便分析系统运行的时间到底消耗在哪里。

使用StopWatch类也很简单。new出实例,调用该实例的start()和stop()方法即可,其实也可以自己手写。

我利用切面的自定义注解,实现代码监视,比较简单直接上代码:

自定义注解:

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TimeProfiling{
}


切面

@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class TimeProfilingAspect {

@Pointcut("@annotation(cn.o2b.aspect.time.TimeProfiling)")
private void timeProfilingPointCut() {}

@Around("timeProfilingPointCut()")
public Object profiling(ProceedingJoinPoint pjp) throws Throwable {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();

try {
return pjp.proceed();
} finally {
stopWatch.stop();
log.info("####{}.{}, {}ms",methodSignature.getMethod().getDeclaringClass().getSimpleName(), methodSignature.getMethod().getName(), stopWatch.getTotalTimeMillis());
}
}
}


附上Java 5.0 Annotation4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明:

@Target

@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。

@Retention

@Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个meta-Annotation可以对 Annotation的“生命周期”限制。例如我们常见的@Override注解,他的@Retention就在source阶段,因为他仅仅是针对方法覆盖进行语法检查,只要符合了规则即可,在运行阶段就不需要了。

@Documented

@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。

@Inherited

@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: