David
David

Reputation: 166

.toNanos() method does not work correctly

I tried to make a method that will give me an idea of how much time it takes to my programs to run, and for an unknown reason, I can not get the nanoseconds.

I tried to read about the below classes but could not find out what I am doing wrong: import java.time.Duration; import java.time.Instant;

The methods:

public static String calcExecutionTime(Instant startTime, Instant endTime) {
    if ((Duration.between(startTime, endTime).toNanos()) < 1000000) {
        return Duration.between(startTime, endTime).toNanos() + " nanoseconds.";
    } else if ((Duration.between(startTime, endTime).toMillis()) < 1000) {
        return Duration.between(startTime, endTime).toMillis() + " milliseconds.";
    } else if ((Duration.between(startTime, endTime).toSeconds()) < 100) {
        return Duration.between(startTime, endTime).toSeconds() + " seconds.";
    } else if ((Duration.between(startTime, endTime).toMinutes()) < 60) {
        return Duration.between(startTime, endTime).toMinutes() + " minutes.";
    } else {
        return Duration.between(startTime, endTime).toHours() + " hoursm.";
    }
}

Main here:

    Instant instantStart = Instant.now();
    Instant instantEnd = Instant.now();
    System.out.print("Execution time for this program: " + calcExecutionTime(instantStart, instantEnd));

If I use the old System.nanoTime(); I get a result of 300-400 nanoseconds but with toNanos() I get 0 in this same situation.

Edit: I do not use getNano() I use toNanos()

Upvotes: 0

Views: 366

Answers (1)

tevemadar
tevemadar

Reputation: 13225

I would go with @Pshemo's comment about Instant.now().

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#now-- :

This will query the system UTC clock to obtain the current instant.

Where the link leads to:

This may use System.currentTimeMillis(), or a higher resolution clock if one is available.

So it may or may not have a higher precision than milliseconds. In your case the "may not have" seems to apply.

Upvotes: 0

Related Questions