如何获取机器的memory和CPU信息?


本文摘自PHP中文网,作者零下一度,侵删。

最近做了一个项目,需要获取机器的CPU和memory的使用情况。花了一些时间网上搜索了一下,自己也做了些测试。总结下来,基本上2种方式:一种是用WMI(2种),另一种是用Performance counter。

1. Use WMI to create connection to the computer passing username and password. Once the connection is created, query the CPU& memory by passing the query, similar as SQL. This way can get CPU & memory for remote PC and local PC. For example:

System.Management.ConnectionOptions Conn = new ConnectionOptions();

Conn.Username = mpusername;

Conn.Password = mppwd;

string scopestring = "//" + mpserver + "/root/cimv2";

System.Management.ManagementScope Ms = new ManagementScope(scopestring);

Ms.Connect();

mos.Scope = Ms;

ObjectQuery oq = new ObjectQuery();

oq.QueryString = "select * from Win32_Processor";

mos.Query = oq;

ManagementObjectCollection moc = mos.Get();

内存这块花了比较多的时间,之前的对象已经过期,不能使用了,最后找到这个类“Win32_PerfRawData_PerfOS_Memory”

ManagementObjectCollection mcr = mcp.getQueryResult("select * from Win32_ComputerSystem");

foreach (ManagementObject mo in mcr)
{
if (mo["TotalPhysicalMemory"] != null)
{
totalm = long.Parse(mo["TotalPhysicalMemory"].ToString());
}
}
ManagementObjectCollection moc = mcp.getQueryResult("select * from Win32_PerfRawData_PerfOS_Memory");
foreach (ManagementObject mo in moc)
{
string avilable = mo.GetPropertyValue("AvailableBytes").ToString();
avilablem = long.Parse(avilable);
}

2. Get local server’s CPU and momory information passing the WMI classes, such as “Win32_Processor”, “Win32_OperatingSystem”

ManagementClass mc = new ManagementClass("Win32_OperatingSystem");

ManagementObjectCollection moc = mc.GetInstances();

3. Use performance counter to get performance data passing the performance counter name, such as monitor.PerformanceCounterFun("Processor", "_Total", "% Processor Time"). Normally we shoud get performance counter data several times, then use the average values.

虽然这些比较简单,但是自己还是想把它记录下来,希望对大家能有用!

以上就是如何获取机器的memory和CPU信息?的详细内容!

相关阅读 >>

分享asp中request对象五个获取客户端资料的方法

介绍asp.net中的mvc如何从控制器传递数据到视图

c#中自定义控件如何实现textbox禁止粘贴的示例代码

asp.net中关于config文件如何读写的实例分享

操作 asp.net web api 的实例教程

关于操作 asp.net web api的实例

怎么操作 asp.net web api ?

具体介绍c#编程获取ip地址的方法

总结mvc中数据验证实例

关于c#winform如何实现右下角弹出窗口结果的方法分享

更多相关阅读请进入《memory》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...