gpt4 book ai didi

java - 为什么它不使用所有处理器?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:49:16 25 4
gpt4 key购买 nike

我编写了一个 java 程序,通过运行大量计算然后将其与我 friend 的计算机进行匹配来测试处理器的能力。

但是,当我运行该程序时,它并没有使用 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();
}

}

这是输出图片:http://i.stack.imgur.com/lH1VA.png

最佳答案

如果您使用的是多处理器机器,您只会使用此代码最大化一个处理器。我要大胆猜测您有 4 个处理器(或 2 个具有超线程)。这可以解释为什么您的利用率仅为 27%。

如果您想真正最大化系统中的所有核心,您还需要启动额外的线程来进行计算。

关于java - 为什么它不使用所有处理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11712034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com