简体   繁体   中英

What is a smart solution for the logging of how much time a task is completed in Java?

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?

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM