Net Core教程

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

本文主要是介绍java调用c#获取多核cpu利用率,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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%

这篇关于java调用c#获取多核cpu利用率的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!