title: What's a clean way to time code execution in Java?
body: <p>It can be handy to time code execution so you know how long things take. However, I find the common way this is done sloppy since it's supposed to have the same indentation, which makes it harder to read what's actually being timed.</p>
  
  <pre><code>long start = System.nanoTime();
  
  // The code you want to time
  
  long end = System.nanoTime();
  System.out.printf("That took: %d ms.%n", TimeUnit.NANOSECONDS.toMillis(end - start));
  </code></pre>
  
  <h2>An attempt</h2>
  
  <p>I came up with the following, it looks way better, there are a few advantages &amp; disadvantages:</p>
  
  <p>Advantages:</p>
  
  <ul>
  <li>It's clear what's being timed because of the indentation</li>
  <li>It will automatically print how long something took after code finishes</li>
  </ul>
  
  <p>Disadvantages:</p>
  
  <ul>
  <li>This is not the way <code>AutoClosable</code> is supposed to be used (pretty sure)</li>
  <li>It creates a new instance of <code>TimeCode</code> which isn't good</li>
  <li>Variables declared within the <code>try</code> block are not accessible outside of it</li>
  </ul>
  
  <p>It can be used like this:</p>
  
  <pre><code> try (TimeCode t = new TimeCode()) {
       // The stuff you want to time
   }
  </code></pre>
  
  <p>The code which makes this possible is:</p>
  
  <pre><code>class TimeCode implements AutoCloseable {
  
      private long startTime;
  
      public TimeCode() {
          this.startTime = System.nanoTime();
      }
  
      @Override
      public void close() throws Exception {
          long endTime = System.nanoTime();
          System.out.printf("That took: %d ms%n",
                  TimeUnit.NANOSECONDS.toMillis(endTime - this.startTime));
      }
  
  }
  </code></pre>
  
  <h2>The question</h2>
  
  <p>My question is:</p>
  
  <ul>
  <li>Is my method actually as bad as I think it is</li>
  <li>Is there a better way to time code execution in Java where you can clearly see what's being timed, or will I just have to settle for something like my first code block.</li>
  </ul>