SpringBoot——》StopWatch 计时器

推荐:

一、简单计时

public class Test {
    public static void main(String[] args) throws InterruptedException {
        getTime();
    }

    public static void getTime() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(100);
        long end = System.currentTimeMillis();

        long start2 = System.currentTimeMillis();
        Thread.sleep(200);
        long end2 = System.currentTimeMillis();

        System.out.println("任务一:" + (end - start));
        System.out.println("任务二:" + (end2 - start2));
    }
}

在这里插入图片描述

二、StopWatch计时

当前使用的SotpWatch

  • 包:spring-core-5.25.RELEASE.jar
  • 类:org.springframework.util.StopWatch
  • start():开始记录,可自定义任务名称
  • stop():停止记录
  • prettyPrint():带格式自动输出各个任务的情况(执行耗时,以及执行时间百分比)
  • getTotalTimeMillis():总用时,单位ms

1、pom依赖

引入 Spring 核心包,Spring MVC 和 Spring Boot 都已经自动引入了该包

<!-- spring核心包 -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${spring.version}</version>
</dependency>

2、JAVA代码

import org.springframework.util.StopWatch;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        getTimeByStopWatch();
    }

    public static void getTimeByStopWatch() throws InterruptedException {
        StopWatch stopWatch = new StopWatch("多个任务用时");
        stopWatch.start("任务一");
        Thread.sleep(100);
        stopWatch.stop();

        stopWatch.start("任务二");
        Thread.sleep(200);
        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint());
        System.out.println("多个任务总用时:"+stopWatch.getTotalTimeMillis()+"毫秒");
    }
}

在这里插入图片描述

3、源码分析

使用 LinkedList 实现了一个叫做 taskList 的数组队列
当任务开始时,使用 System.currentTimeMillis()方法来获取时间
当任务结束时,计算当前任务耗时,并构建一个描述当前任务的 TaskInfo 对象,并把它放入taskList 数组队列

	public void start(String taskName) throws IllegalStateException {
		if (this.currentTaskName != null) {
			throw new IllegalStateException("Can't start StopWatch: it's already running");
		}
		this.currentTaskName = taskName;
		this.startTimeNanos = System.nanoTime();
	}
	
	public void stop() throws IllegalStateException {
		if (this.currentTaskName == null) {
			throw new IllegalStateException("Can't stop StopWatch: it's not running");
		}
		long lastTime = System.nanoTime() - this.startTimeNanos;
		this.totalTimeNanos += lastTime;
		this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
		if (this.keepTaskList) {
			this.taskList.add(this.lastTaskInfo);
		}
		++this.taskCount;
		this.currentTaskName = null;
	}

当任务打印时,执行prettyPrint()方法,从taskList数组队列中依次取出任务,然后进行 格式化输出

	public String prettyPrint() {
		StringBuilder sb = new StringBuilder(shortSummary());
		sb.append('\n');
		if (!this.keepTaskList) {
			sb.append("No task info kept");
		}
		else {
			sb.append("---------------------------------------------\n");
			sb.append("ns         %     Task name\n");
			sb.append("---------------------------------------------\n");
			NumberFormat nf = NumberFormat.getNumberInstance();
			nf.setMinimumIntegerDigits(9);
			nf.setGroupingUsed(false);
			NumberFormat pf = NumberFormat.getPercentInstance();
			pf.setMinimumIntegerDigits(3);
			pf.setGroupingUsed(false);
			for (TaskInfo task : getTaskInfo()) {
				sb.append(nf.format(task.getTimeNanos())).append("  ");
				sb.append(pf.format((double) task.getTimeNanos() / getTotalTimeNanos())).append("  ");
				sb.append(task.getTaskName()).append("\n");
			}
		}
		return sb.toString();
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在Spring Boot中,可以使用StopWatch工具类来计时程序的执行时间。这个工具类位于org.springframework.util包下,可以方便地对程序的部分代码进行计时。\[2\]使用StopWatch比使用System.currentTimeMillis()来计算耗时更方便一些。在Spring Boot中,可以通过创建一个StopWatch对象,调用start()方法开始计时,调用stop()方法停止计时,然后通过调用getTotalTimeSeconds()方法获取总共耗时的秒数。\[1\] 另外,在Spring Boot中也可以使用定时器来执行周期性任务。可以使用scheduleAtFixedRate方法来安排一个任务以固定的速率重复执行。这个方法接受三个参数,分别是TimerTask对象(表示要执行的任务),延迟时间和重复执行的时间间隔。\[3\]在Spring Boot中,可以使用Timer类来创建定时器,并通过调用scheduleAtFixedRate方法来启动定时任务。\[3\]在定时任务的run方法中,可以编写需要周期性执行的代码。例如,可以使用Thread.sleep方法来模拟任务的执行时间,并使用log.info方法来输出日志。\[3\]这样,定时任务就会在指定的延迟后开始执行,并按照指定的时间间隔进行重复执行。\[3\] #### 引用[.reference_title] - *1* *2* [springboot学习(七十四) spring中时钟计时器StopWatch的使用](https://blog.csdn.net/u011943534/article/details/128219115)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [SpringBoot之定时器](https://blog.csdn.net/qq_43654581/article/details/124430268)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值