2018년 3월 30일 금요일

[Java] How to measure execution time ?


1. Measure time with System.nanoTime and System.currentTimeMillis


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
package javautility;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class JavaUtility {

    static void testTimeMeasureNano() throws InterruptedException {
        long start = System.nanoTime();
        Thread.sleep(1200);
        long end = System.nanoTime();
        long diff = end - start;
        System.out.println("Elapsed: " + diff + " nsec, " + 
                TimeUnit.NANOSECONDS.toMillis(diff) + " msec" );
    }
    
    static void testTimeMeasureMillis() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(1200);
        long end = System.currentTimeMillis();
        long diff = end - start;
        System.out.println("Elapsed: " + diff + " msec");
    }
    
    public static void main(String[] args) throws IOException, InterruptedException {
        testTimeMeasureNano();
        System.out.println("----------");
        testTimeMeasureMillis();
    }
}



Result:
Elapsed: 1199611928 nsec, 1199 msec
----------
Elapsed: 1201 msec



2. Measure time with LocalTime


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
package javautility;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalTime;
import java.util.concurrent.TimeUnit;

public class JavaUtility {

    static void timeMeasureLocalTime() throws InterruptedException {
        LocalTime start = LocalTime.now();
        Thread.sleep(1200);
        LocalTime end = LocalTime.now();
        Duration diff = Duration.between(start,end);
        System.out.println("Elapsed: " + diff.toNanos() + " nsec, " + 
                TimeUnit.NANOSECONDS.toMillis(diff.toNanos()) + " msec" );
    }
    public static void main(String[] args) throws IOException, InterruptedException {
        timeMeasureLocalTime();
    }
}



Result:
Elapsed: 1201000000 nsec, 1201 msec









댓글 없음:

댓글 쓰기