写代码时,为了更方便地查看代码用时,通常会在方法开始和结束的地方分别用System.nanoTime取时并计算差值,但是输出结果却看得很别扭,查了下,System.nanoTime()返回的是nanoSeconds,而我们一般都是看的分啊秒啊什么的,可以通过TimeUnit来做nanoSeconds和seconds之间的转换,方便快捷。
TimeUnit是一个枚举类型,它可以做Days, Hours, MicroSeconds, MilliSeconds, Minutes, NanoSeconds之间的转换,API在:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html。
写了简短的代码如下:
package com.geekyjane.cnblogs.nanotime;
import java.util.concurrent.TimeUnit;
public class TransferToSeconds {
public static void main(final String[] args) {
long start = System.nanoTime();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long period = System.nanoTime() - start;
System.out.println(String.format(
"period(nanoseconds): %d, period(seconds): %d", new Object[] {
period, TimeUnit.NANOSECONDS.toSeconds(period) }));
}
}
输出结果为:
period(nanoseconds): 4999610094, period(seconds): 4