在我的应用程序中,我想将应用程序的CPU使用率增加到用户期望的值并使其稳定直到用户兴奋。
我使用top命令使用以下方法计算总CPU使用率。
示例代码:
private long getCpuUsageStatistic() {
usage =0;
String tempString = executeTop(); // executeTop is method where I fire top command.
tempString = tempString.replaceAll(",", "");
tempString = tempString.replaceAll("User", "");
tempString = tempString.replaceAll("System", "");
tempString = tempString.replaceAll("IOW", "");
tempString = tempString.replaceAll("IRQ", "");
tempString = tempString.replaceAll("%", "");
for (int i = 0; i < 10; i++) {
tempString = tempString.replaceAll(" ", " ");
}
tempString = tempString.replaceAll(" ", " ");
tempString = tempString.trim();
String[] myString = tempString.split(" ");
int[] cpuUsageAsInt = new int[myString.length];
for (int i = 0; i < 2; i++) {
myString[i] = myString[i].trim();
cpuUsageAsInt[i] = Integer.parseInt(myString[i]);
//System.out.println("getCpuUsageStatistic-----"+cpuUsageAsInt[i]);
}
usage = cpuUsageAsInt[0]+cpuUsageAsInt[1];
System.out.println("getCpuUsageStatistic-----"+usage);
return usage;
}
And trying to incrase CPU usage by reducing sleeping time of running thread.
but, application COU usage is not increased.
My run method is like following::
public void run() {
while (true) {
try {
Thread.sleep(READ_INTERVAL);
totalUsage += cpuUpdate();
count++;
float cpuUsage = totalUsage / count;
if (count >= 10) {
if (cpuUsage >= desiredCpuUsage) {
System.out.println("cpu usage::%" + cpuUsage);
break;
} else {
System.out.println("cpu usage::%" + cpuUsage);
if(READ_INTERVAL / reducingFactor < 190)
{
if(cpuUsage / desiredCpuUsage< 0.2)
{
reducingFactor = reducingFactor / 1.2;
}
else if(cpuUsage / desiredCpuUsage < 0.5)
{
reducingFactor = reducingFactor / 1.5;
}
else if(cpuUsage / desiredCpuUsage < 0.6)
{
reducingFactor = reducingFactor / 3.0;
}
else if(cpuUsage / desiredCpuUsage < 0.7)
{
reducingFactor = reducingFactor / 4.0;
}
else if(cpuUsage / desiredCpuUsage < 0.75)
{
reducingFactor = reducingFactor / 5.0;
}
else if(cpuUsage / desiredCpuUsage < 0.8)
{
reducingFactor = reducingFactor / 6.0;
}
else if(cpuUsage / desiredCpuUsage < 0.85)
{
reducingFactor = reducingFactor / 7.0;
}
else if(cpuUsage / desiredCpuUsage < 0.9)
{
reducingFactor = reducingFactor / 9.0;
}
else if(cpuUsage / desiredCpuUsage < 0.95)
{
reducingFactor = reducingFactor / 12.0;
}
else
{
reducingFactor = reducingFactor / 15.0;
}
}
READ_INTERVAL-= reducingFactor;
}
cpuUsage=0;
count=0;
System.out.println("Read_interval" + READ_INTERVAL
+ "::cpu usage::%::" + cpuUsage);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
请提供解决方案和任何技术来增加或减少CPU的使用。
提前谢谢。
答案 0 :(得分:0)
我建议在Thread.sleep的while循环中使用一些Math函数来限制它。
我不确定Dalvik VM是否可以被迫接受负载,或者是否会优化其运行时间表以平衡负载。
我只知道很多sin / cos函数创建了一个非常稳定的负载,理论上,只需添加更多或更少的计算就可以轻松扩展和缩小。
我只是不知道VM如何在多核cpu上处理这个问题,因为如果它突然将负载移到另一个核心,第一个核心上的负载会下降或更糟,一直在变化。
但我觉得值得一试