본문 바로가기
개발 언어/Java

[Java] 시간 측정하기 System currentTimeMillis

by 정권이 내 2021. 12. 24.

[Java] 코드 실행시간 측정하기

 

개발을 하다보면 내가 작성한 코드의 효율성을 알아보기 위해 주로 시간을 측정합니다. 또한 어느 부분에서 딜레이가 걸리는지 확인하기 위해 사용할수도 있습니다.

디버깅 중단점을 걸어서 확인할수도 있지만 매번 중단점을 넘겨줘야 해서 코드로 시간을 측정 하는 방법이 편리합니다.

 

Java 현재시간 측정 함수

Java 에서 기본적으로 제공하는 함수중 System.currentTimeMillis 함수를 이용하면 현재 시간을 밀리세컨드 단위로 출력할수 있습니다.

 

[System.currentTimeMillis]

System.java 클래스에 있는 함수 설명을 보면 1970년 1월1일 UTC 시간 기준으로 현재까지의 시간 차이를 밀리 세컨드 단위로 출력한 값입니다.

Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).

Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

 

예제 코드

long 타입 변수 startTime, endTime 에 각각 currentTimeMillis() 값을 입력받도록하고 두 시간의 차이를 밀리 세컨드 단위로 구합니다.

public static void main(String[] args) {

    long startTime = System.currentTimeMillis();

    // 측정할 코드
    for (int j = 0; j < 100000; j++){
        System.out.println("");
    }

    long endTime = System.currentTimeMillis();

    long durationTimeSec = endTime - startTime;
    System.out.println(endTime);
}

 

[실행 결과]

1340
반응형

댓글