时
需求
有时需要记录程序执⾏时间,最简单就是打印当前时间与执⾏完时间的差值,缺点是:
执⾏⼤量测试的话就很⿇烦不直观
如果想对执⾏的时间做进⼀步控制,则需要在程序中很多地⽅修改
于是 Spring提供了⼀个StopWatch类可以做类似任务执⾏时间控制,即封装了⼀个对开始时间,结束时间记录⼯具
案例
统计输出总耗时
import org.springframework.util.StopWatch;
public class SpringStopWatchExample {
public static void main (String[] args) throws InterruptedException { StopWatch sw = new StopWatch(); sw.start();
//long task simulation Thread.sleep(1000); sw.stop();
System.out.println(sw.getTotalTimeMillis()); }}
输出最后⼀个任务的耗时
public class SpringStopWatchExample2 {
public static void main (String[] args) throws InterruptedException { StopWatch sw = new StopWatch(); sw.start(\"A\");//setting a task name //long task simulation Thread.sleep(1000); sw.stop();
System.out.println(sw.getLastTaskTimeMillis()); }}
以优雅的格式打出所有任务的耗时以及占⽐
import org.springframework.util.StopWatch;
public class SpringStopWatchExample3 {
public static void main (String[] args) throws InterruptedException { StopWatch sw = new StopWatch(); sw.start(\"A\");
Thread.sleep(500); sw.stop(); sw.start(\"B\");
Thread.sleep(300); sw.stop(); sw.start(\"C\");
Thread.sleep(200); sw.stop();
System.out.println(sw.prettyPrint()); }}
序列服务输出耗时信息
@Override
public long nextSeq(String name) {
StopWatch watch = new StopWatch(); watch.start(\"单序列获取总消耗\");
long sequence = generator.generateId(name); watch.stop();
logger.info(watch.prettyPrint()); return sequence;}
getTotalTimeSeconds() 获取总耗时秒,同时也有获取毫秒的⽅法prettyPrint() 优雅的格式打印结果,表格形式shortSummary() 返回简短的总耗时描述getTaskCount() 返回统计时间任务的数量
getLastTaskInfo().getTaskName() 返回最后⼀个任务TaskInfo对象的名称
到此这篇关于⽤StopWatch优雅替代currentTimeMillis计算程序执⾏耗时的⽂章就介绍到这了,更多相关Java StopWatch内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务