您好,欢迎访问一九零五行业门户网

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

最近做了一个项目,需要获取机器的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信息?的详细内容。
其它类似信息

推荐信息