如何优雅的计算接口执行时间
最开始想到的办法: 接口开始执行前和执行结束后,分别使用System.currentTimeMillis()方法获取startTime、endTime,endTime-startTime做差得到的就是接口的执行时间,单位是毫秒,一般需要转为秒,再打印出结果
Long startTime = System.currentTimeMillis();//业务逻辑代码............Long endTime = System.currentTimeMillis();Long totalTime = (endTime - startTime) / 1000;System.out.println("该段总共耗时:" + elapsedTime + "s");
上面这种方法可行,但是不够优雅,于是想到了spring框架中提供的StopWatch(秒表)工具类,它是一个简单的秒表工具,使用该方法可以计算出被包裹的代码段的执行时间及总的运行时间,单位为毫秒
代码示范:
//需要引入的包import org.springframework.util.StopWatch;//创建StopWatch 对象StopWatch stopWatch = new StopWatch();//开始计时stopWatch.start("任务1开始:"); Response<List<XXX>> listResponse = clint.XXX(query);//停止计时stopWatch.stop();//打印代码段执行情况System.out.println(stopWatch.prettyPrint());
运行结果:
看着是不是优雅多了,还比较清晰