Search This Blog

Pages

Tuesday, October 25, 2011

A simple counter/timer code in Java

It is a very common requirement to measure time taken by a particular method/function or block of code. The following simple timer can come handy:


long startTime = System.currentTimeMillis();
// Code block or method/function to time.
long endTime = System.currentTimeMillis();
System.out.println("Time taken: " + (endTime - startTime) + " milliseconds");

The accuracy of results can be improved by using System.nanoTime().

No comments:

Post a Comment