// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.Random;

public class GCTest {
    private static final int MIN_LVL = 0;
    private static final int MAX_LVL = 5;
    private static final int MIN_CHLD = 2;
    private static final int MAX_CHLD = 10;
    private static final int NREPL = 100;
    private static int objcount;
    private static final Random rng = new Random();
    private static int getRanInt(int low, int high) {
        return rng.nextInt(high - low + 1) + low;
    }
    private static class AnyObject {
        private Object o;
        public AnyObject(int lvl, int siz) {
            if(lvl > 0) {
                AnyObject[] o2 = new AnyObject[getRanInt(MIN_CHLD, MAX_CHLD)];
                for(int i = 0; i < o2.length; i++) {
                    o2[i] = new AnyObject(lvl - 1, siz);
                }
                o = o2;
            } else {
                o = new byte[getRanInt(0, siz)];
            }
            objcount += 2;
        }
        public Object getObject() {
            return o;
        }
    }
    public static void test(int siz) {
        objcount = 0;
        int topobj = 1000000000 / (int)Math.pow((MAX_CHLD + MIN_CHLD)/2, MAX_LVL) / siz;
        long t1 = System.currentTimeMillis();
        AnyObject[] a = new AnyObject[topobj];
        for(int i = 0; i < NREPL * a.length; i++) {
            a[getRanInt(0, a.length-1)] = new AnyObject(getRanInt(MIN_LVL, MAX_LVL), siz);
        }
        long t2 = System.currentTimeMillis();
        System.out.printf("Objects size 0-%d bytes : %d top objects %.1f million objects in %.1f seconds = %.2f million objects/second\n",
                           siz, topobj, objcount/1000000.0, (t2-t1)/1000.0, objcount/(t2-t1)/1000.0);
    }
    public static void main(String[] args) {
        System.out.println(System.getProperty("java.vendor") + " " + System.getProperty("java.vm.name") + " " + System.getProperty("java.version"));
        test(100);
        test(10000);
    }
}
