How to measure time taken by Java code?

This question already has an answer here:

  • How do I write a correct micro-benchmark in Java? 11 answers

  • You can get nanosecond resolution, even, using System.nanoTime() .

    However, you may want to consider the points in the following:

    How do I write a correct micro-benchmark in Java?


    Say you have a particular method that you would like to put under the microscope. You can do that as follows:

    long time1 = System.nanoTime();
    thatMethod();
    long time2 = System.nanoTime();
    long timeTaken = time2 - time1;  
    System.out.println("Time taken " + timeTaken + " ns");  
    

    Computers are really fast so it may happen that time difference when using getTimeMillis() maybe zero. Hence, use nanoTime()

    You can also use Caliper . They have a video to get started. Plus, thoroughly read the answer pointed to by creichen . It has a lot of great stuff in it.


    Use a library such as Speed4j. This shall not only benchmark the calls but also provide statistics in logs, also you can see them remotely via JMX. It is better of using such a library rather than placing System.current.. calls all over the code.

    链接地址: http://www.djcxy.com/p/86538.html

    上一篇: Java比C更快

    下一篇: 如何测量Java代码所花费的时间?