// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.text.DecimalFormat

nf = new DecimalFormat("0.00")

void printres(long t1, long t2, int n1, int n2, String ops) {
    xperf = n1 * n2 / ((t2 - t1) / 1000.0) 
    sperf = nf.format(xperf / 1000000)
    println("${sperf} million ${ops} per second")
}
    
NINT = 10000
NFP = 10000
NSTR = 10000
N = 10000
    
void testint(int scale) {
    nintscale = NINT.intdiv(scale)
    t1 = System.currentTimeMillis()
    for(i = 0; i < nintscale; i++) {
        int sum = i
        for(j = 0; j < N; j++) {
            sum = ((sum + 1) * 2 + 1).intdiv(2)
        }
        if(sum != (i + N)) {
            println("Integer test error")
            System.exit(1)
        }
    }
    t2 = System.currentTimeMillis()
    printres(t1, t2, nintscale, N, "integer operations")
}

void testfp(int scale) {
    nfpscale = NFP.intdiv(scale)
    t1 = System.currentTimeMillis()
    for(i = 0; i < nfpscale; i++) {
        double sum = i
        for(j = 0; j < N; j++) {
            sum = ((sum + 1) * 2 + 1) / 2
        }
        if(Math.abs(sum - (i + 1.5 * N)) > 1) {
            println("Floating point test error")
            System.exit(1)
        }
    }
    t2 = System.currentTimeMillis()
    printres(t1, t2, nfpscale, N, "floating point operations")
}

ALFA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
VMS_FACTOR = 100

void teststr(int scale) {
    nstrscale = NSTR.intdiv(scale)
    t1 = System.currentTimeMillis()
    for(i = 0; i < nstrscale * VMS_FACTOR; i++) {
        sb = new StringBuffer("")
        for(j = 0; j < N.intdiv(VMS_FACTOR); j = j + 10) {
            s = ALFA + ALFA
            ix = (i + j) % ALFA.length()
            sb << (s[ix .. ix] + s[ix + 1 .. ix + 2] + s[ix + 3 .. ix + 5] + s[ix + 6 .. ix + 9])
        }
        ix1 = N.intdiv(VMS_FACTOR).intdiv(3)
        ix2 = (2 * N.intdiv(VMS_FACTOR)).intdiv(3) 
        if(sb.length() != N.intdiv(VMS_FACTOR) || sb[ix1] != ALFA[(i + ix1) % ALFA.length()] || sb[ix2] != ALFA[(i + ix2) % ALFA.length()]) {
            println("String test error")
            System.exit(1)
        }
    }
    t2 = System.currentTimeMillis()
    printres(t1, t2, nstrscale, N.intdiv(10), "string operations")
}

REP = 10

println("Groovy:")
int scale = 1
if(args.length > 0) {
    scale = Integer.parseInt(args[0])
}
for(i in 1..REP) {
    testint(scale)
}
for(i in 1..REP) {
    testfp(scale)
}
for(i in 1..REP) {
    teststr(scale)
}
