Java 獲取時間間隔的方法

Java中獲取時間間隔的方法比較簡單,通過System.currentTimeMillis()函數即可


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.
See Also:
Date

nanoTime

public static long nanoTime()
Returns the current value of the most precise available system timer, in nanoseconds.

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

For example, to measure how long some code takes to execute:

   long startTime = System.nanoTime();
   // ... the code being measured ...
   long estimatedTime = System.nanoTime() - startTime;
 

Returns:
The current value of the system timer, in nanoseconds.
Since:
1.5

測試currentTimeMillis函數的性能

        final int iLoop = 100000000;


        long lbegin = System.currentTimeMillis();
        for (int i = 0; i < iLoop; ++i)
        {
            System.currentTimeMillis();

        }

        long lend = System.currentTimeMillis();
        System.out.printf("cost : %.3f", (double)(lend - lbegin) / 1000);


執行得到的結果約2秒多,和C/C++的gettimeofday相近,所以可以放心使用

cost : 2.776 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章