我编写了一个java程序,通过运行一定数量的计算然后将其与朋友计算机进行匹配来测试处理器的功能。
但是,当我运行程序时,它不使用100%的处理器。处理能力从1-2%提高到27%,RAM保持在34%。
这只是java或处理器的工作方式吗?或者是我的代码?这是处理计算的类(注意:我还在学习如何编程,我对软件与硬件交互的方式感兴趣):
import javax.swing.JTextPane;
public class Main {
static int numberToCalculate = 100;
static int otherNumberToCalculate = 50;
static String typeOfCalculation = "all";
static int calculated;
static int calculations = 10000000;
public static void calculate(JTextPane j, JTextPane j2) {
long time = System.currentTimeMillis();
for(int i = 0; i <= calculations; i++) {
switch(typeOfCalculation) {
case "Divide":
calculated = numberToCalculate / otherNumberToCalculate;
break;
case "Multiply":
calculated = numberToCalculate * otherNumberToCalculate;
break;
case "Plus":
calculated = numberToCalculate + otherNumberToCalculate;
break;
case "Minus":
calculated = numberToCalculate - otherNumberToCalculate;
break;
case "All":
calculated = numberToCalculate / otherNumberToCalculate;
calculated = calculated * otherNumberToCalculate;
calculated = calculated + otherNumberToCalculate;
calculated = calculated - otherNumberToCalculate;
break;
default:
Test.UpdateText(j, "Error, please pick type of calculation.");
Test.UpdateText(j2, "Error, please pick type of calculation.");
break;
}
if(i == calculations) {
Test.UpdateText(j, "Milliseconds: " + (System.currentTimeMillis() - time));
Test.UpdateText(j2, "Result: " + calculated);
}
}
}
public static void main(String [] args)
{
Test.window();
}
}
答案 0 :(得分:8)
如果您使用的是多处理器计算机,那么您只需使用此代码即可完成一个处理器。我打算走出困境,猜测你有4个处理器(或2个超线程处理器)。这可以解释为什么你的利用率只有27%。
如果您想要真正最大化系统中的所有核心,您还需要启动额外的线程进行计算。
答案 1 :(得分:2)
已经给出了答案:您的代码使用单个线程,无法使用系统的所有容量。您可以尝试下面的程序进行快速测试 - 它首先使用单个线程运行,然后它使用所有处理器(您可能需要根据您的机器增加循环的大小(100,000,000),以便有足够的时间来看到差异):
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Runnable r = new Runnable() {
@Override
public void run() {
double sum = 0;
for (int i = 1; i < 100000000; i++) {
sum += Math.log(i);
}
System.out.println(sum);
}
};
r.run(); //first run: single thread
//second run: as many threads as processors
for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
executor.submit(r);
}
executor.shutdown();
}