title: java measure method invocation rate
body: <p>I want to calculate and print method invocation rate, let's say I have the following method that is called on every consumed message (from Kafka):</p>
  
  <pre><code>public class Consumer {
    public void run() {
     while (true) {
       ConsumerRecords&lt;String&gt; recs = consumer.poll();
       for(ConsumerRecord record: recs) {
         parseMessageToDB(record.getValue());
       }
     }
   }
  
    public void parseMessageToDB(String message) {
      // message parsing logic..
    }
  }
  </code></pre>
  
  <p>My goal here is to calculate #parseMessageToDB method invocations per second to know the speed with that my application can consume events from Kafka.</p>
  
  <p>I tried to use <a href="https://google.github.io/guava/releases/19.0/api/docs/index.html?com/google/common/util/concurrent/RateLimiter.html" rel="nofollow noreferrer">RateLimiter</a> from Guava but it doesn't return the current invocation rate.</p>
  
  <p>Right now I ended up with the following solution where I simply calculate the number of consumed messages in 15sec and simply reset it to zero after logging. </p>
  
  <p>This calculation is not very accurate since I rely on the timer intervals and also there is a possibility to take(or reset) values from another 15sec window, but this gives me at least some picture:</p>
  
  <pre><code>public class Consumer {
  
      private final Timer timer = new Timer();
      private final AtomicLong parsedEvents = new AtomicLong();
      private static final int CONSUMER_TIMER_RATE_SEC = 15;
  
      public Consumer () {
        timer.schedule(new TimerTask() {
          @Override
          public void run() {
          logEventsParsingRate();
          }
        }, 0, CONSUMER_TIMER_RATE_SEC*1000);
  
      }
  
      public void run() {
         while (true) {
           ConsumerRecords&lt;String&gt; recs = consumer.poll();
           for(ConsumerRecord record: recs) {
              parseMessageToDB(record.getValue());
           }
          parsedEvents.addAndGet(recs.count());
         }
       }
  
     private void logEventsParsingRate() {
       logger.info("Consumer events consuming rate per sec: " + 
         handledEvents.getAndSet(0)/CONSUMER_TIMER_RATE_SEC);
     }
  
  }
  </code></pre>
  
  <p>So I'm still looking for any other more accurate solutions. </p>