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

在利用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的子类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值