어제 한 골퍼가 나에게 @SpringBootApplication 주석이 무엇을 의미하는지, Spring Boot가 어떻게 작동하는지 설명해 줄 수 있냐고 물어서 그를 데리고 이 주석과 SpringApplication의 소스 코드를 살펴보았습니다. 클래스의 run() 메소드.
말하지 마세요. 소스 코드를 보는 과정이 정말 흥미롭습니다. 흥미로운 점을 발견했습니다.
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ...... stopWatch.stop(); }
Spring Boot는 시간 소모를 측정하기 위해 StopWatch를 사용하는데, 일반적으로 우리는 시간 소모를 측정하기 위해 System.currentTimeMillis()를 사용합니다. 프로그래밍 야옹???? 오픈 소스 프로젝트에는 통합 로그 처리 측면을 다룰 때 이러한 코드가 있습니다.
@Around("webLog()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis(); webLog.setSpendTime((int) (endTime - startTime)); }
비교해보면 JDK에서 제공하는 System.currentTimeMillis()가 Spring에서 제공하는 StopWatch만큼 간결하고 명확하지 않다는 것을 알 수 있습니다.
특히 멀티태스킹할 때 스톱워치는 너무 사용하기 편해요????!
// 创建一个 StopWatch 实例 StopWatch sw = new StopWatch("沉默王二是傻 X"); // 开始计时 sw.start("任务1"); Thread.sleep(1000); // 停止计时 sw.stop(); System.out.printf("任务1耗时:%d%s.\n", sw.getLastTaskTimeMillis(), "ms"); sw.start("任务2"); Thread.sleep(1100); sw.stop(); System.out.printf("任务2耗时:%d%s.\n", sw.getLastTaskTimeMillis(), "ms"); System.out.printf("任务数量:%s,总耗时:%ss.\n", sw.getTaskCount(), sw.getTotalTimeSeconds());
보세요, 아주 간단하지 않나요?
먼저 새로운 StopWatch 개체를 생성하고
타이밍을 시작한 다음
타이밍을 중지하고
마지막으로 sw.getLastTaskTimeMillis()를 통해 시차를 얻습니다.
만약 System .currentTimeMillis( )로 변경하면 먼저 여러 개의 긴 유형의 지역 변수를 선언한 다음 두 번째 변수에서 첫 번째 변수를 빼고 세 번째 변수에서 두 번째 변수를 빼야 합니다. 약간 부주의하면(특히 CV 방법의 경우) 실수하기 쉽습니다.
현지 시간 외에도 sw.getTotalTimeSeconds()를 통해 총 시간을 얻을 수도 있습니다.
또한 StopWatch는 아름다운 형식의 결과를 인쇄하기 위한 sw.prettyPrint() 메서드도 제공합니다.작업 1은 1002ms가 소요됩니다.
작업 수: 2, 총 소요 시간: 2.107820109초.
스톱워치 '침묵하는 왕얼은 바보야' : 런닝타임 = 2108529351 ns시간 소모량, 점유율, 태스크 이름이 아주 명확하게 나와 있습니다. Spring 외에도 hutool 도구 라이브러리와 Apache 공통 도구 패키지 모두 자체 StopWatch를 제공합니다.------------ ------- -------------
ns % 작업 이름
------------ ------- --------------
1004338467 048% 태스크 1
1104190884 052% 태스크 2
public void stop() throws IllegalStateException { if (null == this.currentTaskName) { throw new IllegalStateException("Can't stop StopWatch: it's not running"); } final long lastTime = System.nanoTime() - this.startTimeNanos; this.totalTimeNanos += lastTime; this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime); if (null != this.taskList) { this.taskList.add(this.lastTaskInfo); } ++this.taskCount; this.currentTaskName = null; }실제로 StopWatch는 System.nanoTime()을 통해 내부적으로 시간이 측정되는 것을 알 수 있는데, 이는 System.currentTimeMillis()와 본질적으로 크게 다르지 않습니다. nanoTime은 currentTimeMillis보다 더 세부적입니다. 전자는 나노초 단위이고 후자는 밀리초 단위입니다.
StopWatch sw = StopWatch.createStarted(); Thread.sleep(1000); System.out.printf("耗时:%dms.\n", sw.getTime());나머지 두 개는 new를 통해 StopWatch 객체를 생성합니다. Commons-lang3은 createStarted(즉시 생성 및 시작) 및 create(생성)를 통해 완료할 수도 있습니다. 또한 타이밍을 일시 중지하기 위해 일시 중지 메서드를 호출하고, 타이밍을 다시 시작하기 위해 재개 메서드를 호출하고, 타이밍을 다시 시작하기 위해 재설정 메서드를 호출할 수도 있습니다.
아아아아
위 내용은 Spring Boot 소스 코드가 StopWatch를 구현하여 시간 소비를 우아하게 계산하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!