Java Millis到纳秒

时间:2013-02-24 11:00:51

标签: java

我刚刚开始学习Java,我想制作随机数组并测量时间。我在填充数组的开头使用了System.currentTimeMillis();,然后在那里使用了long total=TimeUnit.MILLISECONDS.toNanos(time1);。然后我想将毫秒转换为纳秒并使用import java.util.*; import java.util.concurrent.TimeUnit; public class main { public static void main(String[] args) { long time1,time2,time3; int [] array = new int[10]; Random rand =new Random(100); time1=System.currentTimeMillis(); for(int i=0;i<array.length;i++){ array[i]=rand.nextInt(100); } time2=System.currentTimeMillis()-time1; long total=TimeUnit.MILLISECONDS.toNanos(time1); System.out.println("Time is:"+time1 ); } } 但发生了麻烦:

{{1}}

最后我得到'时间是:1361703051169;'我觉得这有点不对劲。

2 个答案:

答案 0 :(得分:4)

好吧,而不是使用

System.currentTimeMillis()

你可以使用

System.nanoTime()

以毫秒为单位提供时间,无需进行任何转换

我认为这也许是错误的:

long total=TimeUnit.MILLISECONDS.toNanos(time1);
System.out.println("Time is:"+time1);

也许您想要打印total而不是time1

修改

请注意,正如Mark Rotteveel所说,System.nanoTimeSystem.currentTimeMillis()不同。

来自Javadocs:

System.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.

System.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.

答案 1 :(得分:0)

您可能想要像这样重写代码:

public static void main(String[] args) {
    long start, end, difference;

    start = System.nanoTime();

    //code to meassure here

    end = System.nanoTime();
    difference = end - start;

    System.out.println("Time taken:" + difference);
}