java调用c#获取多核cpu利用率

24 篇文章 0 订阅

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class ProcessBuilderTest {

public static void main(String[] args) {
List<String> command = new ArrayList<>();
String cmdPath = "E:\\实验\\cpuc#\\ConsoleApp1\\bin\\Debug\\ConsoleApp1.exe";
command.add(cmdPath);
try {
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();
LineNumberReader ir = new LineNumberReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
String lines = new String(), line;
while ((line = ir.readLine()) != null) {
lines += line;
System.out.println(line);
}

if (lines!=null&&lines.trim().length()>0 && lines.contains("Error")) {
String msg = String.format("%s\n", lines);
throw new Exception("运行命令失败:\n" + msg);
}

if(process.isAlive()){
process.waitFor();
}
} catch (Exception e) {
e.printStackTrace();
}
}

}

/


using System;
using System.Diagnostics;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int cnt = System.Environment.ProcessorCount;
PerformanceCounter[] cpuCounter = new PerformanceCounter[cnt];
for (int i = 0; i < cnt; i++)
{
cpuCounter[i] = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
cpuCounter[i].NextValue(); // 这里是为了获得CPU占用率的值
}

//while (true)
{
System.Threading.Thread.Sleep(500 * 1);
for (int i = 0; i < cnt; i++)
{
int id = i + 1;
Console.WriteLine("CPU" + id + "使用率:" + cpuCounter[i].NextValue() + "%");
}

}

//PerformanceCounter cpuCounter;
//PerformanceCounter ramCounter;

//cpuCounter = new PerformanceCounter();
//cpuCounter.CategoryName = "Processor";
//cpuCounter.CounterName = "% Processor Time";
//cpuCounter.InstanceName = "_Total";
//cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
//ramCounter = new PerformanceCounter("Memory", "Available MBytes");

//Console.WriteLine("电脑CPU使用率:" + cpuCounter.NextValue() + "%");
//Console.WriteLine("电脑可使用内存:" + ramCounter.NextValue() + "MB");
//Console.WriteLine();

//while (true)
//{
// System.Threading.Thread.Sleep(1000);
// Console.WriteLine("电脑CPU使用率:" + cpuCounter.NextValue() + " %");
// Console.WriteLine("电脑可使用内存:" + ramCounter.NextValue() + "MB");
// Console.WriteLine();

// if ((int)cpuCounter.NextValue() > 80)
// {
// System.Threading.Thread.Sleep(1000 * 60);
// }
//}
}
}
}

CPU1使用率:3.670228%
CPU2使用率:0.9574056%
CPU3使用率:1.348895%
CPU4使用率:10.86166%

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值