// 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.text.NumberFormat;
import java.text.DecimalFormat;
import java.util.Random;

public class JvmTest {
    private final static int REP = 10;
    private final static int NSTR = 100;
    private final static int N = 1000000;
    private final static String ALFA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static NumberFormat nf = new DecimalFormat("0.00");
    private static Random rng = new Random(); 
    private static int scale;
    private static void printres(long t1, long t2, int n1, int n2, String ops) {
        double xperf = (double)n1 * (double)n2 / ((t2 - t1) / 1000.0) ;
        String sperf= nf.format(xperf/1000000);
        System.out.println(sperf + " million " + ops + " per second");
    }
    public static void teststr() {
        int nstrscale = NSTR / scale;
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < nstrscale; i++) {
            StringBuilder sb = new StringBuilder("");
            for(int j = 0; j < N; j = j + 10) {
                String s = ALFA + ALFA;
                int ix = (i + j) % ALFA.length();
                sb.append(s.substring(ix, ix + 1) + s.substring(ix + 1, ix + 3) + s.substring(ix + 3, ix + 6) + s.substring(ix + 6, ix + 10));
            }
            int ix = rng.nextInt(N);
            if(sb.length() != N || sb.charAt(ix) != ALFA.charAt((i + ix) % ALFA.length())) {
                System.out.println("String test error");
                System.exit(0);
            }
        }
        long t2 = System.currentTimeMillis();
        printres(t1, t2, nstrscale, N / 10, "string operations");
    }
    public static void main(String[] args) {
        System.out.println(System.getProperty("java.vm.vendor") + " " + System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version"));
        if(args.length > 0) {
            scale = Integer.parseInt(args[0]);
        } else {
            scale = 1;
        }
        for(int i = 0; i < REP; i++) {
            teststr();
        }
    }
}
