2013-02-24 62 views
0

我剛開始學習Java,我想製作隨機數組並測量時間。我在填充我的數組時開始使用System.currentTimeMillis();,並且在那時和之後使用System.currentTimeMillis();。然後我就想毫秒轉換爲納秒使用long total=TimeUnit.MILLISECONDS.toNanos(time1);但麻煩出現了:Java Millis to nanoseconds

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;」我認爲這有些問題。

+0

單詞「массив」翻譯爲「陣列」,而不是「大規模」(意思是「массивный」 :) – dasblinkenlight 2013-02-24 11:05:29

+4

我想你需要'的System.out.println (「時間是:」+總數);'並改變使用'time2'而不是'time1' – 2013-02-24 11:05:47

+3

你想告訴我們什麼是錯的? – BobTheBuilder 2013-02-24 11:06:49

回答

0

您可以はNT改寫這樣的代碼:

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); 
} 
4

好,而不是使用

System.currentTimeMillis() 

可以使用

System.nanoTime() 

,它提供了納秒的時間,而無需做任何轉換

此外,我想這也許錯了:

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

也許你想打印total而不是time1

編輯

請注意,馬克Rotteveel說,在System.nanoTimeSystem.currentTimeMillis()是不同的。

從的Javadoc:

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

請注意'System.nanoTime()'不提供與'currentTimeMillis()'相同的時間。 – 2013-02-24 11:12:49

+0

@MarkRotteveel是的,我忘了說這個,我會更新我的答案 – BackSlash 2013-02-24 11:16:10

+0

... OP也很可能在開始和結束時間之間打印出納米級的差異('time2'),而不僅僅是打印開始時間(' time1')納米。 – 2013-02-24 11:18:36