Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AI and Deep Learning by (50.2k points)

How can I measure the speed of code written in Java?

I am planning to develop software which will solve Sudoku using all presently available AI and ML algorithms and compare time against the simple brute-force method. I need to measure the time of each algorithm, I would like to ask for suggestions on what is the best way of doing that? Very important, the program must be useful on any machine regardless of CPU power/memory.

Thank you.

1 Answer

0 votes
by (108k points)

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 milliseconds. We can call this method at the beginning and at the end of the function and by the difference we measure the time taken by the function.

You can refer the following code written in Java:

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 8mili-second

Browse Categories

...