这篇文章将为大家详细讲解有关如何使用StopWatch优雅替代currentTimeMillis计算程序执行耗时,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
有时需要记录程序执行时间,最简单就是打印当前时间与执行完时间的差值,缺点是:
执行大量测试的话就很麻烦
不直观
如果想对执行的时间做进一步控制,则需要在程序中很多地方修改
于是 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计算程序执行耗时”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。