Programming Language/Java

CPU Load Generator

bailey.. 2018. 3. 1. 03:11

https://caffinc.github.io/2016/03/cpu-load-generator/


public class CpuLoadGenerator {
 
    public static void main(String[] args) {
        if (args == null || args.length < 1) {
            throw new IllegalArgumentException("load number is required. (between 0 to 1)");
        }
 
        double load = Double.parseDouble(args[0]);
        int numProcessors = Runtime.getRuntime().availableProcessors();
        long duration = Long.MAX_VALUE;
        if (args.length == 2) {
            try {
                duration = Long.parseLong(args[1]);
            } catch (NumberFormatException e) {
                duration = Long.MAX_VALUE;
            }
        }
 
        System.out.println("CpuLoadGenerator started. numProcessors=" + numProcessors + ", load=" + load);
 
        for (int thread = 0; thread < numProcessors; thread++) {
            new BusyThread("Thread" + thread, load, duration).start();
        }
    }
 
    private static class BusyThread extends Thread {
        private double load;
        private long duration;
 
        public BusyThread(String name, double load, long duration) {
            super(name);
            this.load = load;
            this.duration = duration;
        }
 
        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            try {
                while (System.currentTimeMillis() - startTime < duration) {
                    if (System.currentTimeMillis() % 100 == 0) {
                        Thread.sleep((long) Math.floor((1 - load) * 100));
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
 
cs