언어/JAVA

[JAVA] (조금 더 정확한)실행시간 확인, 측정하기(timer)

벨포트조던 2016. 11. 18.
반응형

http://blog.opid.kr/334




 실행환경

 Notebook

 SAMSUNG NT550p5c-s61r

 CPU

 Intel Core i5-3210M 2.50GHz

 Memory

 8 GB

 OS

 Window 7 ultimate 64bit

 Java

 1.7.0_51

 Android SDK : 4.4.2 (KitKat) / 테스트기기 : Galaxy S3 4.3 (Jelly Bean)

 WebServer

 Apache Tomcat 7.0


코드 실행시간 확인하기

조금 더 정확한 측정 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class TimerTest {
    public static void main(String[] args) {
 
        ExecTime timer = new ExecTime();
        timer.start();
 
        // code
        for (int i = 0; i < 100000000; i++) {
 
        }
        timer.stop();
 
        timer.printExecTime();
        System.out.println(timer.getRunTimeNano() / 1000000 + " ms");
        System.out.println(timer.getRunTimeNano() / 1000000 / 1000 + " sec");
    }
 
}
 
class ExecTime {
    private long start;
    private long stop;
 
    void start() {
        start = System.nanoTime();
    }
 
    void stop() {
        stop = System.nanoTime();
    }
 
    long getRunTimeNano() {
        return stop - start;
    }
 
    void printExecTime() {
        System.out.println(stop - start + " ns");
    }
}

방법1

1
2
3
4
5
6
7
8
9
10
11
12
13
class TimeTest1 {
    public static void main(String[] args) {
 
        long startTime = System.currentTimeMillis();
 
        // code
 
        long stopTime = System.currentTimeMillis();
        long runTime = stopTime - startTime;
 
        System.out.println(runTime);
    }
}

방법 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Stopwatch {
    long start;
    long end;
     
    void start() {
        start = System.currentTimeMillis();
    }
     
    void stop() {
        end = System.currentTimeMillis();
    }
     
    String getRunTime(){
        return end - start + "";
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
class TimeTest2 {
    public static void main(String[] args) {
 
        Stopwatch timer = new Stopwatch().start();
 
        // code
 
        timer.stop();
 
        System.out.println(timer.getRunTime());
    }
}


반응형

댓글