/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;

public class UDFELoops {
    static int maxSize = 10000;
    static Random rng = new Random(3153122688L);
    static volatile int total;
    static Integer[] numbers;

    public static void main(String[] args) throws Exception {
        Class<?> klass = null;
        if (args.length > 0) {
            try {
                klass = Class.forName(args[0]);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Class " + args[0] + " not found.");
            }
        }

        if (args.length > 1)
            maxSize = Integer.parseInt(args[1]);

        System.out.print("Class: " + klass.getName());
        System.out.println(" size: " + maxSize);

        numbers = new Integer[maxSize];
        for (int i = 0; i < maxSize; ++i)
            numbers[i] = rng.nextInt(128);

        long time = 0L;
        for (int i = 0; i < 100; ++i) {
            time += oneRun(klass, (maxSize >> 1) + rng.nextInt(maxSize));
            Thread.sleep(100);
        }

        if (total == 0) System.out.print(" ");
        System.out.println();
        System.out.println("total time " + (time / 1000000) + " ms");
    }

    static long oneRun(Class<?> klass, int n) throws Exception {
        Deque<Integer> q =
            (Deque<Integer>) klass.getConstructor().newInstance();
        int sum = total;
        int m = rng.nextInt(numbers.length);
        long startTime = System.nanoTime();
        for (int k = 0; k < n; ++k) {
            for (int i = 0; i < k; ++i) {
                if (m >= numbers.length)
                    m = 0;
                q.offerFirst(numbers[m++]);
            }
            for (Integer p; (p = q.pollLast()) != null; )
                sum += p.intValue();
        }
        total += sum;
        long endTime = System.nanoTime();
        long time = endTime - startTime;
        long ms = time / 1000000L;
        System.out.print(" " + ms);
        //        double secs = (double) time / 1000000000.0;
        //        System.out.print(" " + secs);
        return time;
    }

}
