// 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.math.BigDecimal;

public class BDSpeedMT {
    private static class Worker extends Thread {
        private int start;
        private int count;
        private BigDecimal sum;
        public Worker(int start, int count) {
            this.start = start;
            this.count = count;
            sum = new BigDecimal(0);
        }
        public void run() {
            BigDecimal v = new BigDecimal("123.500000");
            for(int i = start; i < start + count; i++) {
                sum = sum.add(v);
            }
        }
        public BigDecimal getSum() {
            return sum;
        }
    }
    private static final int N = 1_000_000_000;
    private static void test(int nt) throws InterruptedException {
        long t1 = System.currentTimeMillis();
        int size = N / nt;
        Worker[] t = new Worker[nt];
        for(int i = 0; i < nt; i++) {
            t[i] = new Worker(i * size, size);
        }
        for(int i = 0; i < nt; i++) {
            t[i].start();
        }
        for(int i = 0; i < nt; i++) {
            t[i].join();
        }
        BigDecimal sum = new BigDecimal(0);
        for(int i = 0; i < nt; i++) {
            sum = sum.add(t[i].getSum());
        }
        long t2 = System.currentTimeMillis();
        System.out.printf("%d threads : %.1f seconds (result = %s)\n", nt, (t2 - t1) / 1000.0, sum.toPlainString());
    }
    public static void main(String[] args) throws Exception {
        int nt = 1;
        while(nt < 100) {
            test(nt);
            nt *= 2;
        }
    }
}
