package com.kdgregory.example.benchmark;

/**
 *  A micro-benchmark that includes a "warmup" step, to ensure
 *  that Hotspot is done compiling methods.
 */
public class Micro3
{
    private static final int REPS = 1000000;
    private static final String PART1 = "for a real test, make this big";
    private static final String PART2 = "so that we can see GC effects";
    private static final String REGEX = "XXX";
    private static final String REPL = " -- ";
    private static final String TEMPLATE = PART1 + REGEX + PART2;

    private enum CodeType { concat, replace };


    public static void main(String[] argv)
    throws Exception
    {
        warmup();
        execute();
    }


    private static void warmup()
    {
        System.out.println("running warmup");
        for (int ii = 0 ; ii < 100000 ; ii++)
        {
            // alternating in this way may be voodoo
            executeConcat(1, PART1, PART2, REPL);
            executeReplace(1, TEMPLATE, REGEX, REPL);
        }
    }


    private static void execute()
    {
        System.out.println("running benchmark");
        for (CodeType run : CodeType.values())
        {
            long start = System.currentTimeMillis();
            switch (run)
            {
                case concat :
                    executeConcat(REPS, PART1, PART2, REPL);
                    break;
                case replace :
                    executeReplace(REPS, TEMPLATE, REGEX, REPL);
                    break;
                default :
                    // do nothing
            }
            long elapsed = System.currentTimeMillis() - start;

            System.out.println(run + ": elapsed time = " + elapsed + "ms ("
                                   + (elapsed * 1000.0) / REPS + "microseconds per execution)");
        }
    }


    private static void executeConcat(int reps, String part1, String part2, String repl)
    {
        for (int ii = 0 ; ii < reps ; ii++)
        {
            String s = part1 + repl + part2;
        }
    }


    private static void executeReplace(int reps, String template, String regex, String repl)
    {
        for (int ii = 0 ; ii < reps ; ii++)
        {
            String s = template.replaceAll(regex, repl);
        }
    }
}
