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

前端 未结 30 2538
北荒
北荒 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:53

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

    
        
            io.dropwizard.metrics
            metrics-core
            ${metrics.version}
        
    
    

    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
    

提交回复
热议问题