// 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.util.Arrays;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class VirtualThreadOverhead {
    private static final int ASIZE = 1000;
    private static class Dummy implements Runnable {
        @Override
        public void run() {
            Random rng = new Random();
            int[] a = new int[ASIZE];
            for(int i = 0; i < ASIZE; i++) a[i] = rng.nextInt();
            Arrays.sort(a);
            if(a[0] > a[ASIZE - 1]) throw new RuntimeException("Houston we have a problem");
        }
    }
    private static final int NTASK = 500000;
    private static int measure(int nthreads) throws InterruptedException {
        long t1 = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(nthreads, Thread.builder().virtual().factory());
        for(int i = 0; i < NTASK; i++) {
            es.submit(new Dummy());
        }
        es.shutdown();
        es.awaitTermination(300, TimeUnit.SECONDS);
        long t2 = System.currentTimeMillis();
        return (int)(t2 - t1);
    }
    public static void main(String[] args) throws Exception {
        int[] n = { 1, 2, 3, 4, 5, 6, 7, 8, 9,
                    10, 20, 30, 40, 50, 60, 70, 80, 90,
                    100, 200, 300, 400, 500, 600, 700, 800, 900,
                    1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000,
                    10000 };
        int[] t = new int[n.length];
        for(int i = 0; i < n.length; i++) t[i] = measure(n[i]);
        int mint = Arrays.stream(t).min().getAsInt();
        System.out.printf("%-7s %-7s %s\n", "Threads", "Time", "Performance");
        for(int i = 0; i < n.length; i++) {
            System.out.printf("%7d %7d %5.1f%%\n", n[i], t[i], 100.0 * mint / t[i]);
        }
    }
}
