總網頁瀏覽量

2016年5月30日 星期一

[Java] Java 計算執行時間 01 - time_compute_test_001.java

想要知道 Java 的執行時間意外找到的方法,
但是目前來看好像沒啥用,現在只能當好完試試。

currentTimeMillis 方法

Class lang 底下的 System類別。
除了常用的 out.println() 以外還有這個功能,
但是現在看感覺只是把執行到該程序的時間取出來 ,
在相減來計算所花費的時間,但是可能是目前電腦都比較快,
所以要測試的時候要用大一點的迴圈才感覺得出來。


currentTimeMillis[1]

public static long currentTimeMillis()

    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.
感覺上面這樣描述,時間的計算就是用起出電腦開始計算的時間為初使,
就是1970年開始計算的。

See Also:
        Date



- - - - -
public class time_compute_test_001{
    public static void main(String args[]){
        long time_1;
        long time_2;
        long time_3;
        int a = 0;

        time_1 = System.currentTimeMillis();

        for(int i = 0 ; i < 50 ; i++ ){        }

        time_2 = System.currentTimeMillis();

        for(int i = 0 ; i < 50000000 ; i++ ){
            for(int k = 0 ; k < 50 ; k++ ){
            }
        }

        time_3 = System.currentTimeMillis();
       
        System.out.println(time_1);
        System.out.println(time_2);
        System.out.println(time_3);
       
        System.out.println((time_2-time_1));
        System.out.println((time_3-time_2));
       
    }
}
- - - - -
輸出:

1464602495602
1464602495602
1464602495606
0
4
- - - - -

先宣告兩個長浮點數 long 為參數,放置 currentTimeMillis() 的值。
分別宣告三個參數 time_1、long time_2、long time_3,
之後在彼此之間放置要運算的算式,
我的範例就是兩個不同長度的迴圈,
由於迴圈的執行時間不同,所以迴圈結束後在截取的系統時間也會不同,
從這些時間差的相減來得到運算執行的時間。


從輸出來看,前面兩個時間一樣,
我覺得是因為現在的CUP比較快,對於50個迴圈而言就像一瞬間的事,
所以後兩個時間相比,反而多了4 毫秒的時間差。

- - - - -
[2]

1 = 1000毫秒(ms) 1毫秒                    = 11,000(s) * 目前的回傳時間
1= 1,000,000 微秒(μs) 1微秒            = 11,000,000(s)
1= 1,000,000,000 纳秒(ns) 1纳秒      = 11,000,000,000(s)
1= 1,000,000,000,000 皮秒(ps) 1皮秒= 11,000,000,000,000(s)

- - - - -

[1] https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis%28%29
[2] http://my.oschina.net/xsh1208/blog/183858

沒有留言:

張貼留言