스톱워치 기능은 자주 사용된다. 보통은 다음과 같은 형태로 구현한다. 시스템(System
) 클래스에서 밀리세컨드 현재 밀리세컨드값을 가져와 그 차이를 구하는 방식을 사용한다.
@Test
public void testSimpleTimer() {
long startTime = System.currentTimeMillis();
int data = 0;
for(int i = 0; i < 1_000_000; i++) {
data += 1;
}
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println(elapsedTime);
}
간결하게 사용하기는 나쁘지 않다.
다음 예제는 스프링 프레임워크에서 제공하는 유틸 중 하나인 org.springframework.util.StopWatch
에 대한 간단한 테스트다.
public class StopWatchTest {
private StopWatch stopWatch;
@Before
public void setUp() {
stopWatch = new StopWatch("honeymon");
}
/**
* Long 타입과 BigDecimal 타입의 덧셈 소요시간 비교:
*/
@Test
public void testAddLongAndBigDecimal() {
BigDecimal bigDecimal = BigDecimal.valueOf(0, 0);
Long longType = 0L;
stopWatch.start("Long type");
for(int i = 0; i < 1_000_000; i++) {
longType += 1L;
}
stopWatch.stop();
stopWatch.start("BigDecimal type");
for(int i = 0; i < 1_000_000; i++) {
bigDecimal = bigDecimal.add(BigDecimal.ONE);
}
stopWatch.stop();
System.out.println(stopWatch.shortSummary());
System.out.println(stopWatch.getTotalTimeMillis());
System.out.println(stopWatch.prettyPrint());
}
}
위의 testAddLongAndBigDecimal
테스트를 실행한 결과는 다음과 같다.
StopWatch 'honeymon': running time (millis) = 42 // (1)
42 // (2)
StopWatch 'honeymon': running time (millis) = 42 // (3)
-----------------------------------------
ms % Task name
-----------------------------------------
00017 040% Long type
00025 060% BigDecimal type
Process finished with exit code 0
-
System.out.println(stopWatch.shortSummary());
실행결과 -
System.out.println(stopWatch.getTotalTimeMillis());
실행결과 -
System.out.println(stopWatch.prettyPrint());
실행결과
몇 가지 비교군의 소요시간을 확인해야하는 상황이 있다면 이용해봄직하다.
'Java > Framework & Libs' 카테고리의 다른 글
[spring] 프로파일 조건처리: Profile AND 조건 처리 (2) | 2017.07.24 |
---|---|
Thymeleaf 에서 스프링 환경변수 사용하기 (0) | 2016.12.07 |
[web] HttpServletResponse.sendRedirect 호출시 주의사항 (0) | 2016.11.23 |
[hibernate] org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: (0) | 2016.11.09 |
[spring] 어제의 삽질, ViewController 설정 때문에... (2) | 2016.09.13 |