Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how correctly display nanotime to second conversion

Tags:

java

nanotime

I have a BFS algorithm to solve the 8-Puzzle, and one of the project requirements is to output the amount of time it takes to find the shallowest solution.

I am using System.nanoTime() to keep track of the applications run time because it solves the majority of the given puzzles in well under a second.

The problem i am having is whem i convert my nanoTime to seconds, it displays in a weird format.

the following code is used:

final long startTime = System.nanoTime();

//algorithm code removed for simplicity this all functions correctly


final long duration = System.nanoTime() - startTime;
final double seconds = ((double)duration / 1000000000);
System.out.println("Nano time total: " + duration);
System.out.println("solution Time : " + seconds + " Seconds");

This produces the output:

 Nano time total: 916110
 solution time : 9.1611E-4 Seconds 

I have also tried using floats to represent the values.

is anybody able to provide a better way to convert/display, maybe use a format output statement?

Thanks for taking the time to read my question.

like image 512
chris edwards Avatar asked Nov 02 '13 17:11

chris edwards


People also ask

How do you convert nanoTime to seconds?

We can just divide the nanoTime by 1_000_000_000 , or use the TimeUnit. SECONDS.

How accurate is system nanoTime in Java?

nanoTime() is a great function, but one thing it's not: accurate to the nanosecond. The accuracy of your measurement varies widely depending on your operation system, on your hardware and on your Java version. As a rule of thumb, you can expect microsecond resolution (and a lot better on some systems).

How does system nanoTime work?

nanoTime() method returns the current value of the most precise available system timer, in nanoseconds. The value returned represents nanoseconds since some fixed but arbitrary time (in the future, so values may be negative) and provides nanosecond precision, but not necessarily nanosecond accuracy.

Is system nanoTime unique?

No, there is no guarantee that every call to System. nanoTime() will return a unique value.


2 Answers

I think you need: DecimalFormat

System.out.println("solution Time : " + new DecimalFormat("#.##########").format(seconds) + " Seconds");
like image 58
akasha Avatar answered Nov 14 '22 00:11

akasha


System.out.format("solution Time : %f Seconds", seconds);

for the classic, non-exponential floating point number.

like image 45
Amadan Avatar answered Nov 13 '22 23:11

Amadan