How to convert nanoseconds to seconds using the TimeUnit enum?
Well, you could just divide by 1,000,000,000:
long elapsedTime = end - start;
double seconds = (double)elapsedTime / 1_000_000_000.0;
If you use TimeUnit
to convert, you'll get your result as a long, so you'll lose decimal precision but maintain whole number precision.
TimeUnit
Enum
The following expression uses the TimeUnit
enum (Java 5 and later) to convert from nanoseconds to seconds:
TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS)