优雅的在java中统计代码块耗时

优雅的在java代码中统计代码块耗时

常规写法

long start = System.currentTimeMillis();
try {
    // .... 具体的代码段
} finally {
    System.out.println("cost: " + (System.currentTimeMillis() - start));
}

代理方式

利用Spring AOP中的切面,可以实现无侵入的实现

// 定义切点,拦截所有满足条件的方法
@Pointcut("execution(public * com.boot.aop.demo.*.*(*))")
public void point() {
}

@Around("point()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    long start = System.currentTimeMillis();
    try{
        return joinPoint.proceed();
    } finally {
        System.out.println("cost: " + (System.currentTimeMillis() - start));
    }
}
  • Spring AOP的底层支持原理为代理模式,为目标对象提供增强功能;在Spring的生态体系下,使用aop的方式来统计方法耗时,可以说少侵入且实现简单,但存在:
    • 统计粒度为方法级别
    • 类内部方法调用无法生效

AutoCloseable

在JDK1.7引入了一个新的接口AutoCloseable,通常它的实现类配合try{}使用,可在IO流的使用上。

// 读取文件内容并输出
try (Reader stream = new BufferedReader(new InputStreamReader(new FileInputStream("/tmp")))) {
    List<String> list = ((BufferedReader) stream).lines().collect(Collectors.toList());
    System.out.println(list);
} catch (IOException e) {
    e.printStackTrace();
}
  • 不需要再主动些stream.close:在try(){}执行完毕以后,会调用方法AutoCloseable#close方法

  • 下一个Cost类实现AutoCloseable接口,创建时记录一个时间,close 方法中记录一个时间,并输出时间差值;将需要统计耗时的逻辑放入try(){}代码块

public static class Cost implements AutoCloseable {
    private long start;

    public Cost() {
        this.start = System.currentTimeMillis();
    }

    @Override
    public void close() {
        System.out.println("cost: " + (System.currentTimeMillis() - start));
    }
}

public static void testPrint() {
    for (int i = 0; i < 5; i++) {
        System.out.println("now " + i);
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args) {
    try (Cost c = new Cost()) {
        testPrint();
    }
    System.out.println("------over-------");
}

不管是否抛出异常都会正常输出耗时

总结

  • 基本写法:简单、适用范围广,但是侵入性太强,大量的重复代码
  • Spring AOP:无侵入,适合统一管理。但是适用范围小,且粒度为方法级别,并受限于AOP的使用范围
  • AutoCloseable:基本写法的改良,简单,使用范围广且适合统一管理,但是还是存在侵入
发布了64 篇原创文章 · 获赞 76 · 访问量 9860

猜你喜欢

转载自blog.csdn.net/issunmingzhi/article/details/104803173
今日推荐