Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prove that one algorithm is faster than another in Java

Is there anything in Java that would allow me to take a code snippit and allow me to see exactly how many "ticks" it takes to execute. I want to prove that an algorithm I wrote is faster than another.

like image 944
Jason Thompson Avatar asked Aug 02 '11 23:08

Jason Thompson


1 Answers

"Ticks"? No. I'd recommend that you run them several times each and compare the average results:

public class AlgorithmDriver {
    public static void main(String [] args) {
        int numTries = 1000000;
        long begTime = System.currentTimeMillis();
        for (int i = 0; i < numTries; ++i) {
            Algorithm.someMethodCall();
        }
        long endTime = System.currentTimeMillis();
        System.out.printf("Total time for %10d tries: %d ms\n", numTries, (endTime-begTime));
    }
}
like image 130
duffymo Avatar answered Sep 29 '22 00:09

duffymo