您的位置:首页 > 编程语言 > Java开发

Java 获取时间间隔的方法

2012-04-17 22:04 148 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: