How to measure time taken by a function in java ?

We can measure the time taken by a function in Java with the help of java.lang.System.currentTimeMillis() method. This method returns the current time in millisecond. We can call this method at the beginning and at the end of function and by the difference we measure the time taken by the function.





public class Time {
    public static void main(String[] args)
        // starting time
        long start = System.currentTimeMillis();
        // start of function
        // end of function
        // ending time
        long end = System.currentTimeMillis();
        System.out.println("Counting to 10000000 takes " +
                                    (end - start) + "ms");
    // A dummy function that runs a loop x times
    public static void count_function(long x)
        System.out.println("Loop starts");
        for (long i = 0; i < x; i++)
        System.out.println("Loop ends");



Loop starts
Loop ends
Counting to 10000000 takes 8ms

How to measure time taken by a program in C?

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :


Please write to us at to report any issue with the above content.