C# 怎么获取CPU使用率、可用内存等

C# 怎么获取CPU使用率、可用内存等,第1张

public class CpuInfoCollector

{

[DllImport("kernel32")]

//获取系统内存信息

private static extern void GlobalMemoryStatus(ref MemoryInfor meminfo);

private const string CategoryName = "Processor";

private const string CounterName = "% Processor Time";

private const string InstanceName = "_Total"; //最大内存使用

private float m_MaxMemory=0;

//最大内存使用时间

private DateTime m_MaxMemoryTime=DateTimeNow;

//最小内存使用

private float m_MinMemory;

//最小内存使用时间

private DateTime m_MinMemoryTime = DateTimeNow; //最大Cpu使用

private float m_MaxCpu=0;

//最大Cpu使用时间

private DateTime m_MaxCpuTime = DateTimeNow;

//最小Cpu使用

private float m_MinCpu;

//最小Cpu使用时间

private DateTime m_MinCpuTime = DateTimeNow; /// <summary>

/// 机器性能类(获取CPU使用率)

/// </summary>

private static PerformanceCounter pc;

public DTServerInfoCollector()

{

pc = new PerformanceCounter(CategoryName, CounterName, InstanceName);

}

/// <summary>

/// 获取进程名称

/// </summary>

private static string m_ProcessName = SystemReflectionAssemblyGetExecutingAssembly()GetName()Name;

/// 获取CPU占用率

public float CpuLoad

{

get

{

//实时cpu信息

float cpu = pcNextValue();

if (cpu>MaxCpu)

{

//最大cpu使用赋值

MaxCpu = cpu;

//最大cpu使用时间

MaxCpuTime = DateTimeNow;

}

if (cpu < MinCpu)

{

//最小cpu使用赋值

MinCpu = cpu;

//最小cpu使用时间

MinCpuTime = DateTimeNow;

}

ThreadSleep(500);

return pcNextValue();

}

} //最大内存使用

public float MaxMemory

{

get { return m_MaxMemory; }

set { m_MaxMemory = value; }

} //最大内存使用时间

public DateTime MaxMemoryTime

{

get { return m_MaxMemoryTime; }

set { m_MaxMemoryTime = value; }

}

//最小内存使用

public float MinMemory

{

get { return m_MinMemory; }

set { m_MinMemory = value; }

}

//最小内存使用时间

public DateTime MinMemoryTime

{

get { return m_MinMemoryTime; }

set { m_MinMemoryTime = value; }

}

//最大Cpu使用

public float MaxCpu

{

get { return m_MaxCpu; }

set { m_MaxCpu = value; }

} //最大Cpu使用时间

public DateTime MaxCpuTime

{

get { return m_MaxCpuTime; }

set { m_MaxCpuTime = value; }

}

//最小Cpu使用

public float MinCpu

{

get { return m_MinCpu; }

set { m_MinCpu = value; }

}

//最小Cpu使用时间

public DateTime MinCpuTime

{

get { return m_MinCpuTime; }

set { m_MinCpuTime = value; }

}

/// 获取内存使用

private MemoryInfo GetMemoryInfo()

{

MemoryInfo mInfo = new MemoryInfo();

try

{

MemoryInfor memInfor = GetMemoryInfor();

long lMemoryTotalMB = memInfordwTotalPhys/1024/1024;

long lMemoryAvailMB = memInfordwAvailPhys/1024/1024;

//已经使用内存=最大内存-剩余内存

long lMemoryUsedMB = lMemoryTotalMB - lMemoryAvailMB;

//最大内存

mInfoMemory = lMemoryTotalMB;

if (lMemoryUsedMB>MaxMemory)

{

MaxMemory = lMemoryUsedMB;

MaxMemoryTime = DateTimeNow;

}

if (lMemoryUsedMB < MinMemory)

{

MinMemory = lMemoryUsedMB;

MinMemoryTime = DateTimeNow;

}

//已经使用内存

mInfoMemoryUsed = lMemoryUsedMB;

//最大使用内存

mInfoMaxMemory = MaxMemory;

//最大内存的时间

mInfoMaxMemoryTime = MaxMemoryTime;

//最小使用内存

mInfoMinMemory = MinMemory;

//最小内存的时间

mInfoMinMemoryTime = MinMemoryTime; }

catch (Exception ex)

{

return null;

}

return mInfo; }

/// <summary>

/// 获取系统内存信息

/// </summary>

private MemoryInfor GetMemoryInfor()

{

MemoryInfor memoryInfo = new MemoryInfor();

GlobalMemoryStatus(ref memoryInfo);

return memoryInfo;

}

/// <summary>

/// 获取程序的线程数

/// </summary>

public static int Threads

{

get

{

int i = 0;

try

{

foreach (Process vProcess in ProcessGetProcesses())

{

if (vProcessProcessName == m_ProcessName)

{

i = vProcessThreadsCount;

break;

}

}

}

catch (Exception ex)

{

}

return i;

}

}

}

/// <summary>

/// 定义内存的信息结构

/// </summary>

[StructLayout(LayoutKindSequential)]

public struct MemoryInfor

{

public uint dwLength;

/// <summary>

/// 已经使用的内存

/// </summary>

public uint dwMemoryLoad;

/// <summary>

/// 总物理内存大小

/// </summary>

public uint dwTotalPhys;

/// <summary>

/// 可用物理内存大小

/// </summary>

public uint dwAvailPhys;

/// <summary>

/// 交换文件总大小

/// </summary>

public uint dwTotalPageFile;

/// <summary>

/// 可用交换文件大小

/// </summary>

public uint dwAvailPageFile;

/// <summary>

/// 总虚拟内存大小

/// </summary>

public uint dwTotalVirtual;

/// <summary>

/// 可用虚拟内存大小

/// </summary>

public uint dwAvailVirtual;

}

首先

创建一个Bean用来存贮要得到的信

public class MonitorInfoBean {

/ 可使用内存 /

private long totalMemory;

/ 剩余内存 /

private long freeMemory;

/ 最大可使用内存 /

private long maxMemory;

/ *** 作系统 /

private String osName;

/ 总的物理内存 /

private long totalMemorySize;

/ 剩余的物理内存 /

private long freePhysicalMemorySize;

/ 已使用的物理内存 /

private long usedMemory;

/ 线程总数 /

private int totalThread;

/ cpu使用率 /

private double cpuRatio;

public long getFreeMemory() {

return freeMemory;

}

public void setFreeMemory(long freeMemory) {

thisfreeMemory = freeMemory;

}

public long getFreePhysicalMemorySize() {

return freePhysicalMemorySize;

}

public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {

thisfreePhysicalMemorySize = freePhysicalMemorySize;

}

public long getMaxMemory() {

return maxMemory;

}

public void setMaxMemory(long maxMemory) {

thismaxMemory = maxMemory;

}

public String getOsName() {

return osName;

}

public void setOsName(String osName) {

thisosName = osName;

}

public long getTotalMemory() {

return totalMemory;

}

public void setTotalMemory(long totalMemory) {

thistotalMemory = totalMemory;

}

public long getTotalMemorySize() {

return totalMemorySize;

}

public void setTotalMemorySize(long totalMemorySize) {

thistotalMemorySize = totalMemorySize;

}

public int getTotalThread() {

return totalThread;

}

public void setTotalThread(int totalThread) {

thistotalThread = totalThread;

}

public long getUsedMemory() {

return usedMemory;

}

public void setUsedMemory(long usedMemory) {

thisusedMemory = usedMemory;

}

public double getCpuRatio() {

return cpuRatio;

}

public void setCpuRatio(double cpuRatio) {

thiscpuRatio = cpuRatio;

}

}

之后,建立bean的接口

public interface IMonitorService {

public MonitorInfoBean getMonitorInfoBean() throws Exception;

}

然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。

import javaioInputStreamReader;

import javaioLineNumberReader;

import sunmanagementManagementFactory;

import comsunmanagementOperatingSystemMXBean;

import javaio;

import javautilStringTokenizer;

/

获取系统信息的业务逻辑实现类

@author GuoHuang

/

public class MonitorServiceImpl implements IMonitorService {

private static final int CPUTIME = 30;

private static final int PERCENT = 100;

private static final int FAULTLENGTH = 10;

private static final File versionFile = new File("/proc/version");

private static String linuxVersion = null;

/

获得当前的监控对象

@return 返回构造好的监控对象

@throws Exception

@author GuoHuang

/

public MonitorInfoBean getMonitorInfoBean() throws Exception {

int kb = 1024;

// 可使用内存

long totalMemory = RuntimegetRuntime()totalMemory() / kb;

// 剩余内存

long freeMemory = RuntimegetRuntime()freeMemory() / kb;

// 最大可使用内存

long maxMemory = RuntimegetRuntime()maxMemory() / kb;

OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory

getOperatingSystemMXBean();

// *** 作系统

String osName = SystemgetProperty("osname");

// 总的物理内存

long totalMemorySize = osmxbgetTotalPhysicalMemorySize() / kb;

// 剩余的物理内存

long freePhysicalMemorySize = osmxbgetFreePhysicalMemorySize() / kb;

// 已使用的物理内存

long usedMemory = (osmxbgetTotalPhysicalMemorySize() - osmxb

getFreePhysicalMemorySize())

/ kb;

// 获得线程总数

ThreadGroup parentThread;

for (parentThread = ThreadcurrentThread()getThreadGroup(); parentThread

getParent() != null; parentThread = parentThreadgetParent())

;

int totalThread = parentThreadactiveCount();

double cpuRatio = 0;

if (osNametoLowerCase()startsWith("windows")) {

cpuRatio = thisgetCpuRatioForWindows();

}

else {

cpuRatio = thisgetCpuRateForLinux();

}

// 构造返回对象

MonitorInfoBean infoBean = new MonitorInfoBean();

infoBeansetFreeMemory(freeMemory);

infoBeansetFreePhysicalMemorySize(freePhysicalMemorySize);

infoBeansetMaxMemory(maxMemory);

infoBeansetOsName(osName);

infoBeansetTotalMemory(totalMemory);

infoBeansetTotalMemorySize(totalMemorySize);

infoBeansetTotalThread(totalThread);

infoBeansetUsedMemory(usedMemory);

infoBeansetCpuRatio(cpuRatio);

return infoBean;

}

private static double getCpuRateForLinux(){

InputStream is = null;

InputStreamReader isr = null;

BufferedReader brStat = null;

StringTokenizer tokenStat = null;

try{

Systemoutprintln("Get usage rate of CUP , linux version: "+linuxVersion);

Process process = RuntimegetRuntime()exec("top -b -n 1");

is = processgetInputStream();

isr = new InputStreamReader(is);

brStat = new BufferedReader(isr);

if(linuxVersionequals("24")){

brStatreadLine();

brStatreadLine();

brStatreadLine();

brStatreadLine();

tokenStat = new StringTokenizer(brStatreadLine());

tokenStatnextToken();

tokenStatnextToken();

String user = tokenStatnextToken();

tokenStatnextToken();

String system = tokenStatnextToken();

tokenStatnextToken();

String nice = tokenStatnextToken();

Systemoutprintln(user+" , "+system+" , "+nice);

user = usersubstring(0,userindexOf("%"));

system = systemsubstring(0,systemindexOf("%"));

nice = nicesubstring(0,niceindexOf("%"));

float userUsage = new Float(user)floatValue();

float systemUsage = new Float(system)floatValue();

float niceUsage = new Float(nice)floatValue();

return (userUsage+systemUsage+niceUsage)/100;

}else{

brStatreadLine();

brStatreadLine();

tokenStat = new StringTokenizer(brStatreadLine());

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

tokenStatnextToken();

String cpuUsage = tokenStatnextToken();

Systemoutprintln("CPU idle : "+cpuUsage);

Float usage = new Float(cpuUsagesubstring(0,cpuUsageindexOf("%")));

return (1-usagefloatValue()/100);

}

} catch(IOException ioe){

Systemoutprintln(ioegetMessage());

freeResource(is, isr, brStat);

return 1;

} finally{

freeResource(is, isr, brStat);

}

}

可以考虑使用内存映射文件:javanioMappedByteBuffer,主要适合放入较大的数据进入系统内存

可以考虑使用:javanioByteBufferallocateDirect()方法进行分配,可以将一些不适合放入堆里的数据放入系统内存

还可以采用java本地调用的方式,实现对系统自身内存的掌控与调度,这种方式可以让你灵活的访问系统的内存。

java的堆放入的对象尺度是有限制的,这里建议参考BigMemory 的实现机制以及内存管理机制

如果自己管理内存的话,建议参考其他语言对内存管理的方式。

你可以把数据放入线性数据结构中(这些数据是在系统内存中,而非jvm管理的内存里),这样就不存在分代问题,可以由你的应用在适当的时候清理系统的内存。这样,你的内存模型-释放机制就与jvm的内存管理机制处于一个互不干扰的异行线上。

以上就是关于C# 怎么获取CPU使用率、可用内存等全部的内容,包括:C# 怎么获取CPU使用率、可用内存等、怎么获取 Java 程序使用的内存、怎样用Java获取内存中的数据等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9687221.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-30
下一篇 2023-04-30

发表评论

登录后才能评论

评论列表(0条)

保存