How do I time a method's execution in Java?

前端 未结 30 2542
北荒
北荒 2020-11-21 11:15
  1. How do I get a method\'s execution time?
  2. Is there a Timer utility class for things like timing how long a task takes, etc?

Mos

相关标签:
30条回答
  • 2020-11-21 11:50

    You can use stopwatch class from spring core project:

    Code:

    StopWatch stopWatch = new StopWatch()
    stopWatch.start();  //start stopwatch
    // write your function or line of code.
    stopWatch.stop();  //stop stopwatch
    stopWatch.getTotalTimeMillis() ; ///get total time
    

    Documentation for Stopwatch: Simple stop watch, allowing for timing of a number of tasks, exposing total running time and running time for each named task. Conceals use of System.currentTimeMillis(), improving the readability of application code and reducing the likelihood of calculation errors. Note that this object is not designed to be thread-safe and does not use synchronization. This class is normally used to verify performance during proof-of-concepts and in development, rather than as part of production applications.

    0 讨论(0)
  • 2020-11-21 11:52
    new Timer(""){{
        // code to time 
    }}.timeMe();
    
    
    
    public class Timer {
    
        private final String timerName;
        private long started;
    
        public Timer(String timerName) {
            this.timerName = timerName;
            this.started = System.currentTimeMillis();
        }
    
        public void timeMe() {
            System.out.println(
            String.format("Execution of '%s' takes %dms.", 
                    timerName, 
                    started-System.currentTimeMillis()));
        }
    
    }
    
    0 讨论(0)
  • 2020-11-21 11:53

    If you want wall-clock time

    long start_time = System.currentTimeMillis();
    object.method();
    long end_time = System.currentTimeMillis();
    long execution_time = end_time - start_time;
    
    0 讨论(0)
  • 2020-11-21 11:53

    You can use Metrics library which provides various measuring instruments. Add dependency:

    <dependencies>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>${metrics.version}</version>
        </dependency>
    </dependencies>
    

    And configure it for your environment.

    Methods can be annotated with @Timed:

    @Timed
    public void exampleMethod(){
        // some code
    }
    

    or piece of code wrapped with Timer:

    final Timer timer = metricsRegistry.timer("some_name");
    final Timer.Context context = timer.time();
    // timed code
    context.stop();
    

    Aggregated metrics can exported to console, JMX, CSV or other.

    @Timed metrics output example:

    com.example.ExampleService.exampleMethod
                 count = 2
             mean rate = 3.11 calls/minute
         1-minute rate = 0.96 calls/minute
         5-minute rate = 0.20 calls/minute
        15-minute rate = 0.07 calls/minute
                   min = 17.01 milliseconds
                   max = 1006.68 milliseconds
                  mean = 511.84 milliseconds
                stddev = 699.80 milliseconds
                median = 511.84 milliseconds
                  75% <= 1006.68 milliseconds
                  95% <= 1006.68 milliseconds
                  98% <= 1006.68 milliseconds
                  99% <= 1006.68 milliseconds
                99.9% <= 1006.68 milliseconds
    
    0 讨论(0)
  • 2020-11-21 11:55

    Just a small twist, if you don't use tooling and want to time methods with low execution time: execute it many times, each time doubling the number of times it is executed until you reach a second, or so. Thus, the time of the Call to System.nanoTime and so forth, nor the accuracy of System.nanoTime does affect the result much.

        int runs = 0, runsPerRound = 10;
        long begin = System.nanoTime(), end;
        do {
            for (int i=0; i<runsPerRound; ++i) timedMethod();
            end = System.nanoTime();
            runs += runsPerRound;
            runsPerRound *= 2;
        } while (runs < Integer.MAX_VALUE / 2 && 1000000000L > end - begin);
        System.out.println("Time for timedMethod() is " + 
            0.000000001 * (end-begin) / runs + " seconds");
    

    Of course, the caveats about using the wall clock apply: influences of JIT-compilation, multiple threads / processes etc. Thus, you need to first execute the method a lot of times first, such that the JIT compiler does its work, and then repeat this test multiple times and take the lowest execution time.

    0 讨论(0)
  • 2020-11-21 11:56

    Using Instant and Duration from Java 8's new API,

    Instant start = Instant.now();
    Thread.sleep(5000);
    Instant end = Instant.now();
    System.out.println(Duration.between(start, end));
    

    outputs,

    PT5S
    
    0 讨论(0)
提交回复
热议问题