title: Measuring Java execution time, memory usage and CPU load for a code segment
body: <p><strong>For a particular segment of Java code, I'd like to measure:</strong></p>
  
  <ul>
  <li><strong>Execution time (most likely <em>thread execution time</em>)</strong></li>
  <li><strong>Memory usage</strong></li>
  <li><strong>CPU load (specifically attributable to the code segment)</strong></li>
  </ul>
  
  <p>I'm a relative Java novice and am not familiar with how this might be achieved. I've been referred to <a href="http://en.wikipedia.org/wiki/JMX" rel="nofollow noreferrer">JMX</a>, however I'm not sure how that might be used, and JMX looks a bit 'heavy' for what I'm looking to do.</p>
  
  <p>Ideally I'd like some measurement class that can be told what I would like to measure, with the option of calling a <code>start()</code> method prior to a code segment and a <code>stop()</code> method after. Relevant metrics would be logged to a file I specify.</p>
  
  <p>For example:</p>
  
  <pre><code>import com.example.metricLogger;
  
  metricLogger logger = new metricLogger();
  
  logger.setLogPath(pathToLogFile);
  logger.monitor(executionTime);
  logger.monitor(memoryUsage);
  logger.monitor(cpuLoad);
  
  logger.start();
  
  /* Code to be measured */
  
  logger.stop();
  </code></pre>
  
  <p><strong>Is there any standard/common/conventional way of achieving this in Java?</strong></p>
  
  <p>Such measurements are for one-off performance comparisons, and so I'm not looking for any in-production long-term monitoring processes.</p>
  
  <p>I'm more than happy to be referred to tutorials or external examples and don't expect a full answer here. That said, if anything as simple as the above can be achieved a realistic example would go down really well.</p>