`

编程之美一 : 让CPU占有率曲线听你指挥

 
阅读更多

写一个程序,让用户来决定Windows任务管理器(Task Manager)的CPU占有率。程序越精简越好,可以实现以下三种情况:

/****
 * 
 * 1. JAVA控制CPU的占有率 - 固定在50%,为一条直线
 * 
 ****/
public class CPUTest1 {
	public static void main(String[] args) throws Exception{
		for (;;) {
			for (int i = 0; i < 96000000; i++) {
				;
			}
			Thread.sleep(10);
		}
	}
}

/****
 * 
 * 2. JAVA控制CPU的占有率 - 控制在50%
 * 
 ****/
public class CPUTest2 {
	static int busyTime = 10;
	static int idelTime = busyTime; // 50%的占有率

	public static void main(String[] args) throws Exception {
		long startTime = 0;
		while (true) {
			startTime = System.currentTimeMillis();
			while (System.currentTimeMillis() - startTime < busyTime) {
				;
			}
			Thread.sleep(idelTime);
		}
	}
}

/****
 * 3. JAVA控制CPU的使用率 - 完美曲线
 * 
 * 把一条正弦曲线0~2π之间的弧度等分成200份进行抽样,计算每个抽样点的数据 
 * 然后每隔300ms的时间取下一个抽样点,并让cpu工作对应振幅的时间
 * 
 ****/
public class CPUTest3 {
	public static final int SAMPLING_COUNT = 200; // 抽样点数量 2/RANDIAN_INCREMENT
	public static final double PI = Math.PI; // pi值
	public static final double RANDIAN_INCREMENT = 0.01; // 抽样弧度的增量, 2/SAMPLING_COUNT
	public static final int TOTAL_AMPLITUDE = 300; // 振幅, 每个抽样点对应的时间片

	public static void main(String[] args) throws Exception {//  角度的分割   
		long[] busySpan = new long[SAMPLING_COUNT];
		long[] idleSpan = new long[SAMPLING_COUNT];
		int amplitude = TOTAL_AMPLITUDE / 2;
		double radian = 0.0;
		for (int i = 0; i < SAMPLING_COUNT; i++) {
			busySpan[i] = (long) (amplitude + (Math.sin(PI * radian) * amplitude));
			radian += RANDIAN_INCREMENT;
		}
		long startTime = 0;
		for (int j = 0;; j = (j + 1) % SAMPLING_COUNT) {
			startTime = System.currentTimeMillis();
			while (System.currentTimeMillis() - startTime < busySpan[j]) {
				;
			}
			Thread.sleep(idleSpan[j]);
		}
	}
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics