Timing how long something takes in seconds

时间:2016-07-11 19:42:27

标签: java

I am trying to time how long something takes and i cant get it to spit out the seconds without rounding. Here is what ive tried:

long beginTime = System.nanoTime();
//Do something
long endTime = System.nanoTime();
double time = (endTime-beginTime)/1000000000;

I've also tried using the function TimeUnit.NANOSECONDS.toSeconds and that rounds the number as well.

It should give me 1.45 seconds but it gives me 1 and it should be 1445.7191 Milliseconds but it gives me 1446.

1 个答案:

答案 0 :(得分:2)

the result of your divison is implicitly casted to int, change your divisor to a double value (add a 'd' at the end): 1000000000d

long beginTime = System.nanoTime();
// Do something
long endTime = System.nanoTime();
double time = (endTime - beginTime) / 1000000000d;
System.out.println(time);