ITeye博客

让CPU占用率划出一条直线(Java实现)

walsh · 2009-08-13 10:31 · java · 编程语言 · Markdown

CPU占用率:在任务管理器的一个刷新周期内,CPU忙(执行应用程序)的时间和刷新周期总时间的比率,就是CPU的占用率。 那么如何让CPU占用率曲线听自己指挥呢?以50%为例,用Java代码实现。

public class CPUTest {
	public static void main(String[] args) {
		int busyTime = 10;
		int idleTime = busyTime;
		long startTime = 0;
		while (true) {
			startTime = System.currentTimeMillis();
			// busy loop
			while ((System.currentTimeMillis() - startTime) <= busyTime)
				;
			// idle loop
			try {
				Thread.sleep(idleTime);
			} catch (InterruptedException e) {
				System.out.println(e);
			}
		}
	}
}

运行结果如下:

评论(3)

  1. #3 楼 · atian25 · 2009-08-31 22:55

    试下能否让cpu和io同时保持在90%-95%

  2. #2 楼 · walsh · 2009-08-13 23:00

    mumianiishiwo writes:

    试了下,没看到效果。

    你CPU是单核还是双核? 如果是单核,应该可以的,如果双核打开任务管理器,查看CPU曲线的时候,选择“所有CPU一张图表即可”。在测试的过程中最好别跑别的程序。 :o

  3. #1 楼 · mumianiishiwo · 2009-08-13 14:44

    试了下,没看到效果。

评论功能维护中,当前仅展示历史评论。