// 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
import java.text.NumberFormat

import groovy.transform.*

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

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

@CompileStatic
void teststr(int scale) {
    int NSTR = 10000
    int N = 10000
    String ALFA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    int VMS_FACTOR = 100
    int nstrscale = NSTR.intdiv(scale)
    long t1 = System.currentTimeMillis()
    for(int i = 0; i < nstrscale * VMS_FACTOR; i++) {
        StringBuffer sb = new StringBuffer("")
        for(int j = 0; j < N.intdiv(VMS_FACTOR); j = j + 10) {
            String s = ALFA + ALFA
            int ix = (i + j) % ALFA.length()
            sb << (s[ix .. ix] + s[ix + 1 .. ix + 2] + s[ix + 3 .. ix + 5] + s[ix + 6 .. ix + 9])
        }
        int ix1 = N.intdiv(VMS_FACTOR).intdiv(3)
        int 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)
        }
    }
    long t2 = System.currentTimeMillis()
    printres(t1, t2, nstrscale, N.intdiv(10), "string operations")
}

REP = 10

println("Groovy @CompileStatic:")
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)
}
