Skip to content

Instantly share code, notes, and snippets.

@ihoneymon
Created April 25, 2018 00:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ihoneymon/f312814e41f6525e5359ff0361646d31 to your computer and use it in GitHub Desktop.
Save ihoneymon/f312814e41f6525e5359ff0361646d31 to your computer and use it in GitHub Desktop.

20180425 [spring] StopWatch 기능 테스트

스톱워치 기능은 자주 사용된다. 보통은 다음과 같은 형태로 구현한다. 시스템(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
  1. System.out.println(stopWatch.shortSummary()); 실행결과

  2. System.out.println(stopWatch.getTotalTimeMillis()); 실행결과

  3. System.out.println(stopWatch.prettyPrint()); 실행결과

몇 가지 비교군의 소요시간을 확인해야하는 상황이 있다면 이용해봄직하다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment