The Wayback Machine - https://web.archive.org/web/20221222141802/https://www.geeksforgeeks.org/measure-time-taken-function-java/
Skip to content
Related Articles

Related Articles

How to measure time taken by a function in java ?

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 08 Jan, 2018
Improve Article
Save Article

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.




import java.io.*;
  
public class Time {
    public static void main(String[] args)
    {
        // starting time
        long start = System.currentTimeMillis();
       
        // start of function
  
        count_function(10000000);
  
        // 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");
    }
}

Output:

Loop starts
Loop ends
Counting to 10000000 takes 8ms

How to measure time taken by a program in C?

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!