0

Into a batch Java application (an application that run into the console) I have to log how long it takes to perform a specific task (some operations as a query execution).

So I am thinking that to do it I can retrive the date and time before my task begin and take it again after that the task is completed, then subtract the first value form the second one and use log4j to print the result into a log file.

But, if it is a good solution is correct, how can I correctly take this value (date and time)?

Exist some smarter way to do it?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 1
    Have a look at this thread: http://stackoverflow.com/questions/1770010/how-do-i-measure-time-elapsed-in-java – John Mar 11 '15 at 15:47

2 Answers2

1

Here's an example with a result in milliseconds:

public Connection getConnection(String inConnectionType) throws TSPException {
    long start = System.nanoTime();

    Connection conn = null;
    try {
        DataSource dataSource = getDataSource(inConnectionType);
        conn = dataSource.getConnection();
    } catch (SQLException e) {
        log.error(e);
        throw new TSPException(e);
    }

    long end = System.nanoTime();
    double duration = (end - start) / 1000000.0;

    log.debug("Duration getting external db connection=" + duration);

    return conn;
}
James Hutchinson
  • 841
  • 2
  • 13
  • 27
1

As @John suggested, you can take a look at How do I measure time elapsed in Java?

If you want to measure a few tasks, maybe using System.nanoTime(), storing the values and perform the calculations is enough for you.

If you need something more complex, I would suggest you to take a look at java.time (Java Platform SE 8) or Joda-Time. Both provide the concepts of Duration and Period to measure amounts of time.

Community
  • 1
  • 1
antonio
  • 18,044
  • 4
  • 45
  • 61