// 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) 
public class MemTest {
	private int nobj;
	private int objsiz;
	public MemTest(int nobj, int objsiz) {
		this.nobj = nobj;
		this.objsiz = objsiz;
	}
	public void run() {
		byte[][] a = new byte[nobj][];
		for(int i = 0; i < nobj; i++) {
			a[i] = new byte[objsiz];
		}
		for(int i = 0; i < nobj; i++) {
			for(int j = 0; j < objsiz; j++) a[i][j] = (byte)(i + j);
			Checker.check(a[i]);
		}
		for(int i = 0; i < nobj; i++) {
			a[i] = null;
		}
		a = null;
		System.gc();
	}
	public static long mem() {
		return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
	}
	public static void test(int rep, int nobj, int objsiz) {
		System.gc();
		long m1 = mem();
		long t1 = System.currentTimeMillis();
		for(int i = 0; i < rep; i++) {
			(new MemTest(nobj, objsiz)).run();
		}
		long t2 = System.currentTimeMillis();
		long m2 = mem();
		if(m2 - m1 > 0.01 * nobj * objsiz) throw new RuntimeException("The GC is not running as it should");
		System.out.printf("%d objects of %d bytes : %.3f us per object\n", nobj, objsiz, (t2 - t1) * 1000.0 / (rep * 1.0 * nobj));
	}
	private static final int REP = 1000;
	public static void main(String[] args) {
		for(int i = 1; i <= 4; i++) {
			for(int j = 1; j <= 4; j++) {
				test(REP, i * 1000000, j * 10);
			}
		}
		test(10 * REP, 10, 1000000);
	}
}
