具体实例代码如下:
首先是获取本机中所有进程对象,分别输出某一时刻各个进程的.内存使用情况:
using Systemusing System.Collections.Genericusing System.Linqusing System.Textusing System.Diagnosticsusing System.Threadingnamespace CSharpPerformance{//该程序可以实时监控所有进程或者指定进程的工作集、私有工作集 class Program { static void Main(string[] args) { //新建一个Stopwatch变量用来统计程序运行时间 Stopwatch watch = Stopwatch.StartNew()//获取本机运行的所有进程ID和进程名,并输出哥进程所使用的工作集和私有工作集 foreach (Process ps in Process.GetProcesses()) { PerformanceCounter pf1 = new PerformanceCounter("Process", "Working Set - Private", ps.ProcessName)PerformanceCounter pf2 = new PerformanceCounter("Process", "Working Set", ps.ProcessName)Console.WriteLine("{0}:{1} {2:N}KB", ps.ProcessName, "工作集(进程类)", ps.WorkingSet64 / 1024)Console.WriteLine("{0}:{1} {2:N}KB", ps.ProcessName, "工作集 ", pf2.NextValue() / 1024)//私有工作集 Console.WriteLine("{0}:{1} {2:N}KB", ps.ProcessName, "私有工作集 ", pf1.NextValue() / 1024)} watch.Stop()Console.WriteLine(watch.Elapsed)Console.ReadLine()} }}
其中,工作集ps.WorkingSet64是静态的,pf2.NextValue()是动态变化的,工作集包含进程运行时其独占的内存和与其他进程共享的内存的和,而私有工作集是只包含进程独占的内存。
下面一组代码可以动态显示本程序所对应的进程的CPU和内存使用率的变化:
首先是SystemInfo.cs类:
using Systemusing System.Collections.Genericusing System.Diagnosticsusing System.Threadingusing System.IOusing System.Textusing System.Managementusing System.Runtime.InteropServicesnamespace CSharpPerformance{ public class SystemInfo { private int m_ProcessorCount = 0//CPU个数 private PerformanceCounter pcCpuLoad//CPU计数器 private long m_PhysicalMemory = 0//物理内存 private const int GW_HWNDFIRST = 0private const int GW_HWNDNEXT = 2private const int GWL_STYLE = (-16)private const int WS_VISIBLE = 268435456private const int WS_BORDER = 8388608#region AIP声明 [DllImport("IpHlpApi.dll")] extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder)[DllImport("User32")] private extern static int GetWindow(int hWnd, int wCmd)[DllImport("User32")] private extern static int GetWindowLongA(int hWnd, int wIndx)[DllImport("user32.dll")] private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize)[DllImport("user32", CharSet = CharSet.Auto)] private extern static int GetWindowTextLength(IntPtr hWnd)#endregion #region 构造函数 ///
/// 构造函数,初始化计数器等 ///
public SystemInfo() { //初始化CPU计数器 pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total")pcCpuLoad.MachineName = "."pcCpuLoad.NextValue()//CPU个数 m_ProcessorCount = Environment.ProcessorCount//获得物理内存 ManagementClass mc = new ManagementClass("Win32_ComputerSystem")ManagementObjectCollection moc = mc.GetInstances()foreach (ManagementObject mo in moc) { if (mo["TotalPhysicalMemory"] != null) { m_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString())} } } #endregion #region CPU个数 ///
/// 获取CPU个数 ///
public int ProcessorCount { get { return m_ProcessorCount} } #endregion #region CPU占用率 ///
/// 获取CPU占用率 ///
public float CpuLoad { get { return pcCpuLoad.NextValue()} } #endregion #region 可用内存 ///
/// 获取可用内存 ///
public long MemoryAvailable { get { long availablebytes = 0//ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfOS_Memory")//foreach (ManagementObject mo in mos.Get()) //{ // availablebytes = long.Parse(mo["Availablebytes"].ToString())//} ManagementClass mos = new ManagementClass("Win32_OperatingSystem")foreach (ManagementObject mo in mos.GetInstances()) { if (mo["FreePhysicalMemory"] != null) { availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString())} } return availablebytes} } #endregion #region 物理内存 ///
/// 获取物理内存 ///
public long PhysicalMemory { get { return m_PhysicalMemory} } #endregion #region 结束指定进程 ///
/// 结束指定进程 ///
///
进程的 Process IDpublic static void EndProcess(int pid) { try { Process process = Process.GetProcessById(pid)process.Kill()} catch { } } #endregion #region 查找所有应用程序标题 ///
/// 查找所有应用程序标题 ///
///
应用程序标题范型
public static List
FindAllApps(int Handle) { ListApps = new List()int hwCurrhwCurr = GetWindow(Handle, GW_HWNDFIRST)while (hwCurr >0) { int IsTask = (WS_VISIBLE | WS_BORDER)int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE)bool TaskWindow = ((lngStyle &IsTask) == IsTask)if (TaskWindow) { int length = GetWindowTextLength(new IntPtr(hwCurr))StringBuilder sb = new StringBuilder(2 * length + 1)GetWindowText(hwCurr, sb, sb.Capacity)string strTitle = sb.ToString()if (!string.IsNullOrEmpty(strTitle)) { Apps.Add(strTitle)} } hwCurr = GetWindow(hwCurr, GW_HWNDNEXT)} return Apps} #endregion }}
然后是执行代码:
using Systemusing System.Collections.Genericusing System.Linqusing System.Textusing System.Diagnosticsusing System.Threadingnamespace CSharpPerformance{//该程序可以实时监控程序本身对应进程的工作集、私有工作集和CPU使用率 class Program { static void Main(string[] args) { //获取当前进程对象 Process cur = Process.GetCurrentProcess()PerformanceCounter curpcp = new PerformanceCounter("Process", "Working Set - Private", cur.ProcessName)PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", cur.ProcessName)PerformanceCounter curtime = new PerformanceCounter("Process", "% Processor Time", cur.ProcessName)//上次记录CPU的时间 TimeSpan prevCpuTime = TimeSpan.Zero//Sleep的时间间隔 int interval = 1000PerformanceCounter totalcpu = new PerformanceCounter("Processor", "% Processor Time", "_Total")SystemInfo sys = new SystemInfo()const int KB_DIV = 1024const int MB_DIV = 1024 * 1024const int GB_DIV = 1024 * 1024 * 1024while (true) { //第一种方法计算CPU使用率 //当前时间 TimeSpan curCpuTime = cur.TotalProcessorTime//计算 double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100prevCpuTime = curCpuTimeConsole.WriteLine("{0}:{1} {2:N}KB CPU使用率:{3}", cur.ProcessName, "工作集(进程类)", cur.WorkingSet64 / 1024,value)//这个工作集只是在一开始初始化,后期不变 Console.WriteLine("{0}:{1} {2:N}KB CPU使用率:{3}", cur.ProcessName, "工作集 ", curpc.NextValue() / 1024,value)//这个工作集是动态更新的 //第二种计算CPU使用率的方法 Console.WriteLine("{0}:{1} {2:N}KB CPU使用率:{3}%", cur.ProcessName, "私有工作集 ", curpcp.NextValue() / 1024,curtime.NextValue()/Environment.ProcessorCount)//Thread.Sleep(interval)//第一种方法获取系统CPU使用情况 Console.Write("r系统CPU使用率:{0}%", totalcpu.NextValue())//Thread.Sleep(interval)//第二章方法获取系统CPU和内存使用情况 Console.Write("r系统CPU使用率:{0}%,系统内存使用大小:{1}MB({2}GB)", sys.CpuLoad, (sys.PhysicalMemory - sys.MemoryAvailable) / MB_DIV, (sys.PhysicalMemory - sys.MemoryAvailable) / (double)GB_DIV)Thread.Sleep(interval)} Console.ReadLine()} }}
以上程序可以正常运行,没隔1S刷新一次,实现动态显示本程序对应进程的CPU和内存使用情况。
首先创建一个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) {
this.freeMemory = freeMemory
}
public long getFreePhysicalMemorySize() {
return freePhysicalMemorySize
}
public void setFreePhysicalMemorySize(long freePhysicalMemorySize) {
this.freePhysicalMemorySize = freePhysicalMemorySize
}
public long getMaxMemory() {
return maxMemory
}
public void setMaxMemory(long maxMemory) {
this.maxMemory = maxMemory
}
public String getOsName() {
return osName
}
public void setOsName(String osName) {
this.osName = osName
}
public long getTotalMemory() {
return totalMemory
}
public void setTotalMemory(long totalMemory) {
this.totalMemory = totalMemory
}
public long getTotalMemorySize() {
return totalMemorySize
}
public void setTotalMemorySize(long totalMemorySize) {
this.totalMemorySize = totalMemorySize
}
public int getTotalThread() {
return totalThread
}
public void setTotalThread(int totalThread) {
this.totalThread = totalThread
}
public long getUsedMemory() {
return usedMemory
}
public void setUsedMemory(long usedMemory) {
this.usedMemory = usedMemory
}
public double getCpuRatio() {
return cpuRatio
}
public void setCpuRatio(double cpuRatio) {
this.cpuRatio = cpuRatio
}
}
之后,建立bean的接口
public interface IMonitorService {
public MonitorInfoBean getMonitorInfoBean() throws Exception
}
然后,就是最关键的,得到cpu的利用率,已用内存,可用内存,最大内存等信息。
import java.io.InputStreamReader
import java.io.LineNumberReader
import sun.management.ManagementFactory
import com.sun.management.OperatingSystemMXBean
import java.io.*
import java.util.StringTokenizer
/**
* 获取系统信息的业务逻辑实现类.
* @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 = Runtime.getRuntime().totalMemory() / kb
// 剩余内存
long freeMemory = Runtime.getRuntime().freeMemory() / kb
// 最大可使用内存
long maxMemory = Runtime.getRuntime().maxMemory() / kb
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
.getOperatingSystemMXBean()
// *** 作系统
String osName = System.getProperty("os.name")
// 总的物理内存
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb
// 剩余的物理内存
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb
// 已使用的物理内存
long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
.getFreePhysicalMemorySize())
/ kb
// 获得线程总数
ThreadGroup parentThread
for (parentThread = Thread.currentThread().getThreadGroup()parentThread
.getParent() != nullparentThread = parentThread.getParent())
int totalThread = parentThread.activeCount()
double cpuRatio = 0
if (osName.toLowerCase().startsWith("windows")) {
cpuRatio = this.getCpuRatioForWindows()
}
else {
cpuRatio = this.getCpuRateForLinux()
}
// 构造返回对象
MonitorInfoBean infoBean = new MonitorInfoBean()
infoBean.setFreeMemory(freeMemory)
infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize)
infoBean.setMaxMemory(maxMemory)
infoBean.setOsName(osName)
infoBean.setTotalMemory(totalMemory)
infoBean.setTotalMemorySize(totalMemorySize)
infoBean.setTotalThread(totalThread)
infoBean.setUsedMemory(usedMemory)
infoBean.setCpuRatio(cpuRatio)
return infoBean
}
private static double getCpuRateForLinux(){
InputStream is = null
InputStreamReader isr = null
BufferedReader brStat = null
StringTokenizer tokenStat = null
try{
System.out.println("Get usage rate of CUP , linux version: "+linuxVersion)
Process process = Runtime.getRuntime().exec("top -b -n 1")
is = process.getInputStream()
isr = new InputStreamReader(is)
brStat = new BufferedReader(isr)
if(linuxVersion.equals("2.4")){
brStat.readLine()
brStat.readLine()
brStat.readLine()
brStat.readLine()
tokenStat = new StringTokenizer(brStat.readLine())
tokenStat.nextToken()
tokenStat.nextToken()
String user = tokenStat.nextToken()
tokenStat.nextToken()
String system = tokenStat.nextToken()
tokenStat.nextToken()
String nice = tokenStat.nextToken()
System.out.println(user+" , "+system+" , "+nice)
user = user.substring(0,user.indexOf("%"))
system = system.substring(0,system.indexOf("%"))
nice = nice.substring(0,nice.indexOf("%"))
float userUsage = new Float(user).floatValue()
float systemUsage = new Float(system).floatValue()
float niceUsage = new Float(nice).floatValue()
return (userUsage+systemUsage+niceUsage)/100
}else{
brStat.readLine()
brStat.readLine()
tokenStat = new StringTokenizer(brStat.readLine())
tokenStat.nextToken()
tokenStat.nextToken()
tokenStat.nextToken()
tokenStat.nextToken()
tokenStat.nextToken()
tokenStat.nextToken()
tokenStat.nextToken()
String cpuUsage = tokenStat.nextToken()
System.out.println("CPU idle : "+cpuUsage)
Float usage = new Float(cpuUsage.substring(0,cpuUsage.indexOf("%")))
return (1-usage.floatValue()/100)
}
} catch(IOException ioe){
System.out.println(ioe.getMessage())
freeResource(is, isr, brStat)
return 1
} finally{
freeResource(is, isr, brStat)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)