Java中StopWatch工具类的用法详解
stopWatch 是org.springframework.util 包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比。
在未使用这个工具类之前,如果我们需要统计某段代码的耗时,我们会这样写:
public static void main(String[] args) throws InterruptedException {
test0();
}
public static void test0() throws InterruptedException {
long start = System.currentTimeMills();
// do something
Thread.sleep(100);
long end = System.currentTimeMills();
long start2 = System.currentTimeMills();
// do somethind
long end2 = System.currentTimeMills();
System.out.println("某某1执行耗时:" + (end -start));
System.out.println("某某2执行耗时:" + (end2 -start2));
}如果改用stopWatch 实现的一个示例
public class StopWatchDemo {
public static void main(String[] args) throws InterruptedException {
test1();
}
public static void test1() throws InterruptedException {
StopWatch sw = new StopWatch("test");
sw.start("task1");
// do something
Thread.sleep(100);
sw.stop();
sw.start("task2");
// do someting
Thread.sleep(200);
sw.stop();
System.out.println("sw.prettyPrint()-------");
System.out.println(sw.prettyPrint());
}
}运行结果如下:
sw.prettyPrint()------
StopWatch 'test': running time (millis) = 310
-----------------------------------------
ms % Task name
-----------------------------------------
00110 035% task1
00200 065% task2
通过start 与stop 方法分别记录开始时间与结束时间,其中在记录结束时间的时候,会维护一个链表类型的taskList 属性,从而时该类可记录多个任务,最后的输出页仅仅是对之前的记录信息做了一个统一的归纳输出。
import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List;
public class StopWatch {
private final String id;
private boolean keepTaskList = true;
private final List<TaskInfo> taskList = new LinkedList();
private long startTimeMillis;
private boolean running;
private String currentTaskName;
private StopWatch.TaskInfo lastTaskInfo;
private int taskCount;
private long totalTimeMillis;
public StopWatch() {
this.id = "";
}
public StopWatch(String id) {
this.id = id;
}
public void setKeepTaskList(boolean keepTaskList) {
this.keepTaskList = keepTaskList;
}
public void start() throws IllegalStateException {
this.start("");
}
public void start(String taskName) throws IllegalStateException {
if (this.running) {
throw new IllegalStateException("Can't start StopWatch: it's already running");
} else {
this.startTimeMillis = System.currentTimeMillis();
this.running = true;
this.currentTaskName = taskName;
}
}
public void stop() throws IllegalStateException {
if (!this.running) {
throw new IllegalStateException("Can't stop StopWatch: it's not running");
} else {
long lastTime = System.currentTimeMillis() - this.startTimeMillis;
this.totalTimeMillis += lastTime;
this.lastTaskInfo = new StopWatch.TaskInfo(this.currentTaskName, lastTime);
if (this.keepTaskList) {
this.taskList.add(this.lastTaskInfo);
}
++this.taskCount;
this.running = false;
this.currentTaskName = null;
}
}
public boolean isRunning() {
return this.running;
}
public long getLastTaskTimeMillis() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task interval");
} else {
return this.lastTaskInfo.getTimeMillis();
}
}
public String getLastTaskName() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task name");
} else {
return this.lastTaskInfo.getTaskName();
}
}
public StopWatch.TaskInfo getLastTaskInfo() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task info");
} else {
return this.lastTaskInfo;
}
}
public long getTotalTimeMillis() {
return this.totalTimeMillis;
}
public double getTotalTimeSeconds() {
return (double) this.totalTimeMillis / 1000.0D;
}
public int getTaskCount() {
return this.taskCount;
}
public StopWatch.TaskInfo[] getTaskInfo() {
if (!this.keepTaskList) {
throw new UnsupportedOperationException("Task info is not being kept!");
} else {
return (StopWatch.TaskInfo[]) this.taskList.toArray(new StopWatch.TaskInfo[this.taskList.size()]);
}
}
public String shortSummary() {
return "StopWatch '" + this.id + "': running time (millis) = " + this.getTotalTimeMillis();
}
public String prettyPrint() {
StringBuilder sb = new StringBuilder(this.shortSummary());
sb.append('\n');
if (!this.keepTaskList) {
sb.append("No task info kept");
} else {
sb.append("-----------------------------------------\n");
sb.append("ms % Task name\n");
sb.append("-----------------------------------------\n");
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumIntegerDigits(5);
nf.setGroupingUsed(false);
NumberFormat pf = NumberFormat.getPercentInstance();
pf.setMinimumIntegerDigits(3);
pf.setGroupingUsed(false);
StopWatch.TaskInfo[] var7;
int var6 = (var7 = this.getTaskInfo()).length;
for (int var5 = 0; var5 < var6; ++var5) {
StopWatch.TaskInfo task = var7[var5];
sb.append(nf.format(task.getTimeMillis())).append(" ");
sb.append(pf.format(task.getTimeSeconds() / this.getTotalTimeSeconds())).append(" ");
sb.append(task.getTaskName()).append("\n");
}
}
return sb.toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(this.shortSummary());
if (this.keepTaskList) {
StopWatch.TaskInfo[] var5;
int var4 = (var5 = this.getTaskInfo()).length;
for (int var3 = 0; var3 < var4; ++var3) {
StopWatch.TaskInfo task = var5[var3];
sb.append("; [").append(task.getTaskName()).append("] took ").append(task.getTimeMillis());
long percent = Math.round(100.0D * task.getTimeSeconds() / this.getTotalTimeSeconds());
sb.append(" = ").append(percent).append("%");
}
} else {
sb.append("; no task info kept");
}
return sb.toString();
}
public static final class TaskInfo {
private final String taskName;
private final long timeMillis;
TaskInfo(String taskName, long timeMillis) {
this.taskName = taskName;
this.timeMillis = timeMillis;
}
public String getTaskName() {
return this.taskName;
}
public long getTimeMillis() {
return this.timeMillis;
}
public double getTimeSeconds() {
return (double) this.timeMillis / 1000.0D;
}
}
}到此这篇关于Java中StopWatch工具类的用法详解的文章就介绍到这了,更多相关Java StopWatch内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot配置文件中数据库密码加密两种方案(推荐)
SpringBoot项目经常将连接数据库的密码明文放在配置文件里,安全性就比较低一些,尤其在一些企业对安全性要求很高,因此我们就考虑如何对密码进行加密,文中给大家介绍加密的两种方式,感兴趣的朋友一起看看吧2019-10-10
GC调优实战之高分配速率High Allocation Rate
这篇文章主要为大家介绍了GC调优之高分配速率High Allocation Rate的实战示例分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步2022-01-01
关于Spring Boot项目的 log4j2 核弹漏洞问题(一行代码配置搞定)
相信昨天,很多小伙伴都因为Log4j2的史诗级漏洞忙翻了吧,不过我看到群里发出来的各种修复方法,还真是不好看...所以这里也提一下Spring Boot用户怎么修复最简单吧,对Spring Boot log4j2 核弹漏洞问题感兴趣的朋友参考下吧2021-12-12
spring data jpa 查询自定义字段,转换为自定义实体方式
这篇文章主要介绍了spring data jpa 查询自定义字段,转换为自定义实体方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-06-06


最新评论