0

我刚开始学习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
    );

}

}

最后我得到'时间是:1361703051169;' 我认为这有问题。

4

2 回答 2

5

好吧,而不是使用

System.currentTimeMillis()

您可以使用

System.nanoTime()

这提供了以纳秒为单位的时间,而无需进行任何转换

我也认为这可能是错误的:

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

也许你想打印total而不是time1

编辑

请注意,正如 Mark Rotteveel 所说,在System.nanoTimeandSystem.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.

于 2013-02-24T11:04:37.053 回答
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);
}
于 2013-02-24T11:23:34.270 回答