-2

This is a college job.

Java language / I use Eclipse IDE

I need to count the running time of my program.

I want to print the runtime.

Example:

import java.time.LocalDateTime;

...
LocalDateTime start;
LocalDateTime end;

start = LocalDateTime.now();

...
xx my code xxx
...

end = LocalDateTime.now();

<<here I have doubts

I need to calculate "end - start" and pass the result to String

  • Does this answer your question? [Java 8: Difference between two LocalDateTime in multiple units](https://stackoverflow.com/questions/25747499/java-8-difference-between-two-localdatetime-in-multiple-units) – Eritrean Oct 07 '21 at 16:57
  • 1
    @Eritrean Not really a duplicate of that specific Question. Given the context presented here, `LocalDateTime` is the wrong class to accomplish this person’s goal. Thus, [my Answer](https://stackoverflow.com/a/69486393/642706). – Basil Bourque Oct 07 '21 at 18:59
  • [Measure Elapsed Time in Java | Baeldung](https://www.baeldung.com/java-measure-elapsed-time). [How do I time a method's execution in Java?](https://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java) I downvoted because it seems you forgot to search prior to posting your question(?) – Ole V.V. Oct 08 '21 at 19:14

1 Answers1

2

tl;dr

Duration              // Represent a span-of-time unattached to the timeline on a scale of hours-minutes-seconds. 
.between(             // Calculate time elapsed between two `Instant` objects. 
    then ,            // An `Instant` object instantiated earlier.
    Instant.now()     // Capture the current moment as seen in UTC (an offset of zero hours-minutes-seconds). 
)                     // Returns a `Duration` object.
.toString()           // Generate text in standard ISO 8601 format.

LocalDateTime cannot represent a moment

LocalDateTime is the wrong class for tracking specific points on the timeline. That class purposely lacks the context of a time zone or offset-from-UTC. So it cannot represent a moment. I cannot imagine a scenario where calling LocalDateTime.now() is the right thing to do.

For example, if you were to calculate elapsed time during which a Daylight Saving Time (DST) cut-over occurred, your result would be incorrect. The LocalDateTime class ignores any offset changes in that time zone.

Track elapsed time with java.time.Instant

Instead, use Instant.

Instant start = Instant.now() ;
…
Instant end = Instant.now() ;

Represent elapsed time with java.time.Duration

Calculate elapsed time using Duration class.

Duration elapsed = Duration.between( start , end ) ;

Generate text in standard ISO 8601 format: PnYnMnDTnHnMnS. Example: PT30M for exactly one half-hour.

String output = elapsed.toString() ;

To generate text in other formats, access the parts by calling to…Part methods.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154