在java程序分析运行时间的时候常常会统计代码块的耗时,在此简单介绍三种方法。
常规写法
1long start = System.currentTimeMillis();
2try {
3 // .... 具体的代码段
4} finally {
5 System.out.println("cost: " + (System.currentTimeMillis() - start));
6}
代理方式
利用Spring AOP中的切面,可以实现无侵入的实现
1// 定义切点,拦截所有满足条件的方法
2@Pointcut("execution(public * com.boot.aop.demo.*.*(*))")
3public void point() {
4}
5
6@Around("point()")
7public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
8 long start = System.currentTimeMillis();
9 try{
10 return joinPoint.proceed();
11 } finally {
12 System.out.println("cost: " + (System.currentTimeMillis() - start));
13 }
14}
Spring AOP的底层支持原理为代理模式,为目标对象提供增强功能;在Spring的生态体系下,使用aop的方式来统计方法耗时,可以说少侵入且实现简单,但存在:
统计粒度为方法级别
类内部方法调用无法生效
AutoCloseable
在JDK1.7引入了一个新的接口AutoCloseable,通常它的实现类配合try{}使用,可在IO流的使用上。
1// 读取文件内容并输出
2try (Reader stream = new BufferedReader(new InputStreamReader(new FileInputStream("/tmp")))) {
3 List list = ((BufferedReader) stream).lines().collect(Collectors.toList());4 System.out.println(list);5} catch (IOException e) {6 e.printStackTrace();7}
不需要再主动写stream.close:在try(){}执行完毕以后,会调用方法AutoCloseable#close方法
下一个Cost类实现AutoCloseable接口,创建时记录一个时间,close 方法中记录一个时间,并输出时间差值;将需要统计耗时的逻辑放入try(){}代码块
1public static class Cost implements AutoCloseable {
2 private long start;
3
4 public Cost() {
5 this.start = System.currentTimeMillis();
6 }
7
8 @Override 9 public void close() {
10 System.out.println("cost: " + (System.currentTimeMillis() - start));
11 }
12}
13
14public static void testPrint() {
15 for (int i = 0; i 5; i++) {
16 System.out.println("now " + i);
17 try {
18 Thread.sleep(10);
19 } catch (InterruptedException e) {
20 e.printStackTrace();
21 }
22 }
23}
24
25public static void main(String[] args) {
26 try (Cost c = new Cost()) {
27 testPrint();
28 }
29 System.out.println("------over-------");
30}
不管是否抛出异常都会正常输出耗时
总结
基本写法:简单、适用范围广,但是侵入性太强,大量的重复代码
Spring AOP:无侵入,适合统一管理。但是适用范围小,且粒度为方法级别,并受限于AOP的使用范围
AutoCloseable:基本写法的改良,简单,使用范围广且适合统一管理,但是还是存在侵入
最后
如果觉得看完有收获,希望能给我点个赞,这将会是我更新的最大动力,感谢各位的支持
欢迎各位关注我的公众号【java冢狐】,专注于java和计算机基础知识,保证让你看完有所收获,不信你打我
如果看完有不同的意见或者建议,欢迎多多评论一起交流。感谢各位的支持以及厚爱。