我刚刚开始学习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
);
}
}
Run Code Online (Sandbox Code Playgroud)
最后我得到了“时间是:1361703051169;” 我认为这有问题。
好吧,而不是使用
System.currentTimeMillis()
Run Code Online (Sandbox Code Playgroud)
您可以使用
System.nanoTime()
Run Code Online (Sandbox Code Playgroud)
这提供了以纳秒为单位的时间,无需进行任何转换
我也认为这可能是错误的:
long total=TimeUnit.MILLISECONDS.toNanos(time1);
System.out.println("Time is:"+time1);
Run Code Online (Sandbox Code Playgroud)
也许您想打印total而不是time1?
编辑
请注意,正如 Mark Rotteveel 所说, 中 和System.nanoTime是System.currentTimeMillis()不同的。
来自 Java 文档:
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.
| 归档时间: |
|
| 查看次数: |
2154 次 |
| 最近记录: |