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

}

}

最後に、「Time is: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.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.

于 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 に答える