Get the time difference between two times in java8

At work, we often want to check the performance of a method execution, we will calculate the time difference at the entrance and exit of the method, like the following code:

        long start = System.currentTimeMillis();

        //business code
        Thread.sleep(1000);

        long over = System.currentTimeMillis();

        System.out.println("business used " + (over - start) + " ms");

Then in java8 we have a new class that can do the same operation, as follows:

        Instant now = Instant.now();

        //business code
        Thread.sleep(2000);

        long used = ChronoUnit.MILLIS.between(now, Instant.now());

        //或者
        //long used =now.until(Instant.now(), ChronoUnit.MILLIS)
        
        System.out.println("business used " + used + " ms");
System.currentTimeMillis()只能精确到毫秒,如果你有更高的要求,要精确到纳秒,java8可以轻松搞定:
long used = ChronoUnit.NANOS.between(now, Instant.now());

If your environment is java8, it is recommended that you use the latest syntax to get the time difference!

If you get the number of days between two dates, it is recommended to read another article: Java8 realizes the calculation of the number of days between two dates

 

Guess you like

Origin blog.csdn.net/kevin_mails/article/details/87794060