码迷,mamicode.com
首页 > 其他好文 > 详细

cpu占用率曲线-笔记

时间:2017-08-31 20:25:37      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:函数   今天   目的   div   sleep   运行   static   cep   方法   

我们知道要查看电脑的cpu占用率的话可以从任务管理器得知,进一步可以从->性能栏 看到CPU占用率的曲线的变化。今天看了编程之美的第一章第一节,看到对电脑cpu占用率的控制,控制CPU占用率曲线变化,达到特定的效果。

cpu占用率曲线的刷新频率为1秒。要使在某一时刻CPU占用率达到目的中的百分比,可通过分配1秒内程序运行和休眠的时间的所占比,来达到。如在某1秒内,程序都处于休眠状态,那么,CPU占用率将达到0(理想化)。反正,cpu占用率将达到100%。

第一种方法:基于计算程序所运行的电脑CPU主频,而得到的循环次数参数(根据电脑配置而定),该参数是10毫秒内,CPU运行循环40500000次。

public static void main(String[] args) throws InterruptedException {
        for (;;){
             for (int i=0;i<40500000;i++);
             Thread.sleep(10);
         }
    }

二:根据所占时间比重

public static final int BUSYTIME=10;
public static final int IDLETIME=BUSYTIME;
public
static void main(String[] args) throws InterruptedException { while(true){ long startTime=System.currentTimeMillis();//获取开始时间 while(System.currentTimeMillis()-startTime<=BUSYTIME){ }; Thread.sleep(IDLETIME); } }

三:画个正弦

public static final double PI=3.1415926535;
public static final int X_COUNT=200;//200百个抽样点,画个正弦函数
public static final int TIME=300;//每个点的时间片,单位毫秒
 //正弦函数Y=TIME/2 + TIME/2*Math.sin(i*PI/100)
 //思路:先计算每个时间片内,busy和idle分别所运行的时间,之后进行循环运行
public
static void main(String[] args) throws InterruptedException { int busy[]=new int[200]; for (int i = 0; i < X_COUNT; i++) { busy[i]=(int) (TIME/2 + TIME/2*Math.sin(i*PI/100)); System.out.println(busy[i]); } while(true){ for (int i = 0; i < busy.length; i++) { long startTime=System.currentTimeMillis();//获取开始时间 while(System.currentTimeMillis()-startTime<=busy[i]){ System.out.println(i); System.out.println(busy[i]); }; Thread.sleep(TIME-busy[i]); } System.out.println("一个周期"); } }

 

cpu占用率曲线-笔记

标签:函数   今天   目的   div   sleep   运行   static   cep   方法   

原文地址:http://www.cnblogs.com/xumz/p/7460200.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!