Month: October 2014

Java Timing Code: Compare Execution Times of Methods

Often times, you will have two Java functions, and you will want to know which one performs better. You can use this Java class to time multiple methods to find out which one is faster.

Example Usage: Java Timing Code

Let’s say you have these two functions and want to know which one is faster:

public static String function1(String i) {
    return i + i;
}

public static String function2(String i) {
    StringBuilder sb = new StringBuilder();
    sb.append(i);
    sb.append(i);
    return sb.toString();
}

Here is how you would use my timing class:

public static void simpleTimingTest() throws Exception {
    Timing t = new Timing();

    /*
    The timing function will run the tests in chunks.
    For each chunk, the same input will be used.

    Input will be gathered via the passed IntFunction. The timing method will
    pass the current index (going from 0 to amountRunsPerChunk) to it and will expect
    any return of the defined type.
    */
    IntFunction inputProvider = i -> String.valueOf(i);

    /*
    The add method expects two functions: the above mentioned input provider,
    as well as a function which accepts the output from the input provider as input
    and applies it to the function which will be timed.
    */
    t.add((String s) -> function1(s), inputProvider, "function1 ");
    t.add((String s) -> function2(s), inputProvider, "function2 ");

    t.time(true); // true: force test (otherwise, time might throw an exception
                  // if it suspects that there isn't enough memory)
    t.output(s -> System.out.println(s), Timing.Sort.ASC);
}

You can also do more complex things with it:

public static void predefinedInputTimingTest() throws Exception {
    Timing t = new Timing();
    /*
    The input doesn't have to be generated using the passed index, you could
    also use predefined input to time your functions:
    */
    String[] input = new String[]{"input1", "another input", "more input"};
    IntFunction inputProvider = i -> input[i % input.length];
    t.add((String s) -> function1(s), inputProvider, "function1 ");
    t.add((String s) -> function2(s), inputProvider, "function2 ");

    /*
    You can decide what should be reported when timing finished:
    */
    t.setReport(EnumSet.of(Timing.Report.NAME, Timing.Report.MEAN));
    t.setAmountChunks(1_500);
    t.setAmountRunsPerChunk(2_500);
    t.time(true, s -> System.out.println(s)); // pass String -> String function to report debug information
    t.output(s -> System.out.println(s), Timing.Sort.ASC);
}