如何获取当前进程的获取进程cpu使用率率,内存使用率

Windows下用C语言获取进程cpu使用率,内存使用,IO情况
Windows下用C语言获取进程cpu使用率,内存使用,IO情况一个项目需要,特地写了这些功能的函数。pocess_stat.h的内容如下:C代码1.**@file2.*@ief进程统计信息函数的声明3.*@autho张亚霏4.*@date200905035.*@vesion0.16.*7.*8.#ifndefPROCESS_STAT_H9.#definePROCESS_STAT_H10.11.12.#ifdef__cplusplus13.exten"C"{14.#endif15.16.typedeflonglongint64_t;17.typedefunsignedlonglonguint64_t;18.19.20.获取当前进程的cpu使用率,返回-1失败21.intget_cpu_usage();22.23.24.获取当前进程内存和虚拟内存使用量,返回-1失败,0成功25.intget_memoy_usage(uint64_t*mem,uint64_t*vmem);26.27.28.获取当前进程总共读和写的IO字节数,返回-1失败,0成功29.intget_io_ytes(uint64_t*ead_ytes,uint64_t*wite_ytes);30.31.32.33.
& 果果文库所有资源均来源于互联网,仅供网友学习交流,若侵犯了您的权益,请联系我们予以删除。
3062&&人浏览
8411&&人浏览
1007&&人浏览
15438&&人浏览
18365&&人浏览
856&&人浏览
4781&&人浏览
11523&&人浏览
16562&&人浏览
15494&&人浏览
16896&&人浏览
103&&人浏览
1656&&人浏览
7972&&人浏览
15329&&人浏览
本文标题:Windows下用C语言获取进程cpu使用率,内存使用,IO情况 链接地址:
2013- Inc. All Rights Reserved 果果文库 版权所有 联系站长: ; 经营许可证编号:浙ICP备号首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程对象。当有了进程对象后,可以通过进程对象名称来创建PerformanceCounter类型对象,通过设定PerformanceCounter构造函数的参数实现获取特定进程的CPU和内存使用情况。
具体实例代码如下:
首先是获取本机中所有进程对象,分别输出某一时刻各个进程的内存使用情况:
2 using System.Collections.G
3 using System.L
4 using System.T
5 using System.D
6 using System.T
8 namespace CSharpPerformance
9 {//该程序可以实时监控所有进程或者指定进程的工作集、私有工作集
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类:
2 using System.Collections.G
3 using System.D
4 using System.T
5 using System.IO;
6 using System.T
7 using System.M
8 using System.Runtime.InteropS
10 namespace CSharpPerformance
public class SystemInfo
private int m_ProcessorCount = 0;
private PerformanceCounter pcCpuL
//CPU计数器
private long m_PhysicalMemory = 0;
//物理内存
private const int GW_HWNDFIRST = 0;
private const int GW_HWNDNEXT = 2;
private const int GWL_STYLE = (-16);
private const int WS_VISIBLE = ;
private 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 构造函数
/// &summary&
/// 构造函数,初始化计数器等
/// &/summary&
public SystemInfo()
//初始化CPU计数器
pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
pcCpuLoad.MachineName = ".";
pcCpuLoad.NextValue();
m_ProcessorCount = Environment.ProcessorC
//获得物理内存
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个数
/// &summary&
/// 获取CPU个数
/// &/summary&
public int ProcessorCount
return m_ProcessorC
#endregion
#region CPU占用率
/// &summary&
/// 获取CPU占用率
/// &/summary&
public float CpuLoad
return pcCpuLoad.NextValue();
#endregion
#region 可用内存
/// &summary&
/// 获取可用内存
/// &/summary&
public long MemoryAvailable
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());
#endregion
#region 物理内存
/// &summary&
/// 获取物理内存
/// &/summary&
public long PhysicalMemory
return m_PhysicalM
#endregion
#region 结束指定进程
/// &summary&
/// 结束指定进程
/// &/summary&
/// &param name="pid"&进程的 Process ID&/param&
public static void EndProcess(int pid)
Process process = Process.GetProcessById(pid);
process.Kill();
#endregion
#region 查找所有应用程序标题
/// &summary&
/// 查找所有应用程序标题
/// &/summary&
/// &returns&应用程序标题范型&/returns&
public static List&string& FindAllApps(int Handle)
List&string& Apps = new List&string&();
hwCurr = 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);
#endregion
然后是执行代码:
2 using System.Collections.G
3 using System.L
4 using System.T
5 using System.D
6 using System.T
8 namespace CSharpPerformance
9 {//该程序可以实时监控程序本身对应进程的工作集、私有工作集和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.Z
//Sleep的时间间隔
int interval = 1000;
PerformanceCounter totalcpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
SystemInfo sys = new SystemInfo();
const int KB_DIV = 1024;
const int MB_DIV = 1024 * 1024;
const int GB_DIV = 1024 * 1024 * 1024;
while (true)
//第一种方法计算CPU使用率
//当前时间
TimeSpan curCpuTime = cur.TotalProcessorT
double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;
prevCpuTime = curCpuT
Console.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和内存使用情况。
阅读(...) 评论()如何像任务管理器一样获取每个进程的CPU占用率和内存占用呢?【c++吧】_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:290,327贴子:
如何像任务管理器一样获取每个进程的CPU占用率和内存占用呢?收藏
c++培训课程,美国上市公司&达内&出品c++课程,15年教学经验,总监级c++讲师亲授!!达内首创&先就业后付款&模式.名企项目总监授课,成就&稀缺级&c/c++软件工程师
up.继续求.
POSIX里有查看程序占用的CPU时间的函数吗?
具体的哪个函数?谢谢
求具体哪个API?
Win7 Pcwum.dllPcwCreateQuery
PcwAddQueryItem PcwCollectData
XP的路过..
登录百度帐号推荐应用用户名:hakuyo
文章数:34
访问量:11000
注册日期:
阅读量:1297
阅读量:3317
阅读量:454109
阅读量:1138806
51CTO推荐博文
分享一下自己做的一个获取windows系统状态的类(c++)使用方式:声明一个该类的变量(即实例化),用实例调用相关接口即可。头文件:#ifndef WinSystemInfo_include
#define WinSystemInfo_include
#include &winsock2.h&
#include &ws2tcpip.h&
#include &Iphlpapi.h&
#include &windows.h&
#include &string&
#include &vector&
namespace WINSERV_STATE
#pragma pack(push)
#pragma pack(8)
struct sys_mem_info
//总内存数,单位M
//可用内存数,单位M
struct sys_net_info
//每秒发送流量
//每秒接受流量
//每秒钟总流量
struct DiskInfo
//总数单位M
//可用空间数单位M
struct sys_process_info
//进程cpu使用率
//进程内存大小
struct process_time_info
//process id
//time spent in kernel mode
//time spent in user mode
//上次时间
enum connection_type{UNKNOWN=0,TCP,UDP,TCP6,UDP6};
struct sys_conn_info
connection_
#if (WINVER&=0x0600)
MIB_TCP6ROW
MIB_UDP6ROW
MIB_TCPROW
MIB_UDPROW
struct SysNetConnInfo
std::string
std::string
#pragma pack(pop)
DWORD WINAPI CountCpuUsage(LPVOID lpParameter);
class WinSystemInfo
WinSystemInfo(void);
~WinSystemInfo(void);
//获取可用百分比
getDiskAvailable();
//获取磁盘总空间和空闲空间
getDrivesInfo(std::vector&DiskInfo&& drives,ULONGLONG& totalSpace, ULONGLONG& totalFreeSpace);
//get memory info
GetMemInfo(sys_mem_info& info);
//connection info
GetConnInfo(std::vector&SysNetConnInfo&& conns);
//return cpu usage 0~100
GetCpuInfo();
//net flow info
sys_net_info
GetNetInfo();
//process info
GetProcInfo(std::vector&sys_process_info&& procInfo);
friend DWORD WINAPI CountCpuUsage(LPVOID lpParameter);
//内部使用变量
CompareFileTime(const FILETIME& time1,const FILETIME& time2);
Get_processor_number();
CRITICAL_SECTION
sys_net_info
//net flow info
std::vector&sys_process_info&
WinSystemInfo(const WinSystemInfo&);
WinSystemInfo& operator= (const WinSystemInfo&);
initialize();
m_totalDiskS
m_hCpuCountT
#endif源文件:#include &winsock2.h&
//#include &ws2tcpip.h&
#include &tlhelp32.h&
#include &stdlib.h&
//#include &stdio.h&
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
#include "WinSystemInfo.h"
//#include &iomanip&//for get cpu usage
#include "psapi.h"
#pragma comment(lib,"Iphlpapi.lib")
#pragma comment(lib,"ws2_32.lib")
//#pragma comment(lib,"Advapi32.lib")
#pragma comment(lib,"psapi.lib")
#include &direct.h&
namespace WINSERV_STATE
DWORD WINAPI CountCpuUsage(LPVOID lpParameter)
PROCESSENTRY32
procKernelT
std::vector&process_time_info&
WinSystemInfo* p = (WinSystemInfo*)lpP
FILETIME preidleT
FILETIME prekernelT
FILETIME preuserT
FILETIME idleT
FILETIME kernelT
FILETIME userT
//total cpu usage
res = GetSystemTimes( &idleTime, &kernelTime, &userTime );
return GetLastError();
preidleTime
prekernelTime
preuserTime
= CreateEvent(NULL,FALSE,FALSE,NULL);
MIB_IFTABLE *pIfTable
= (MIB_IFTABLE *) MALLOC(sizeof (MIB_IFTABLE));
//MIB_IFROW *pIfR
static __int64 net_send = 0;
static __int64 net_recv = 0;
DWORD dwRet
DWORD dwSize
= sizeof (MIB_IFTABLE);
//获取初始网络流量数据
if (GetIfTable(pIfTable, &dwSize, FALSE) == ERROR_INSUFFICIENT_BUFFER) {
FREE(pIfTable);
= (MIB_IFTABLE *) MALLOC(dwSize);
if (pIfTable == NULL) {
return GetLastError();
dwRet = GetIfTable(pIfTable,&dwSize,FALSE);
if ( dwRet == NO_ERROR )
for (DWORD i=0; i & pIfTable-&dwNumE i++ ){
+= (__int64)(pIfTable-&table[i].dwOutOctets);
+= (__int64)(pIfTable-&table[i].dwInOctets);
//process infos
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
return GetLastError();
pe32.dwSize = sizeof( PROCESSENTRY32 );
if( !Process32First( hProcessSnap, &pe32 ))
CloseHandle( hProcessSnap );
return GetLastError();
GetSystemTimeAsFileTime(&sysTime);
process_time_info
= OpenProcess(PROCESS_ALL_ACCESS/*PROCESS_QUERY_INFORMATION | PROCESS_VM_READ*/, FALSE, pe32.th32ProcessID );
if( hP == NULL )
procTime.pid
= (int)pe32.th32ProcessID;
procTime.lastSysTime
GetProcessTimes(hP,&creatTime,&exitTime,&procTime.kernelTime,&procTime.userTime);
procTimeInfo.push_back(procTime);
CloseHandle(hP);
} while(Process32Next( hProcessSnap, &pe32));
CloseHandle( hProcessSnap );
int processorCount
= p-&Get_processor_number();
if(WaitForSingleObject( hEvent,1000) == WAIT_FAILED )
return GetLastError();
res = GetSystemTimes( &idleTime, &kernelTime, &userTime );
return GetLastError();
= p-&CompareFileTime( preidleTime,idleTime);
= p-&CompareFileTime( prekernelTime, kernelTime);
= p-&CompareFileTime(preuserTime, userTime);
double cpu
= (((double)(kernel + user - idle)/(double)(kernel+user))*100+0.5);
if((UINT)cpu != 0)
EnterCriticalSection(&p-&m_cpu_critical);
p-&m_cpuUsage =
LeaveCriticalSection(&p-&m_cpu_critical);
preidleTime
prekernelTime
preuserTime
//计算网络流量
= GetIfTable(pIfTable,&dwSize,FALSE);
if ( dwRet == NO_ERROR )
total_send
total_recv
for (DWORD i=0; i & pIfTable-&dwNumE i++ )
total_send
+= pIfTable-&table[i].dwOutO
total_recv
+= pIfTable-&table[i].dwInO
EnterCriticalSection(&p-&m_cpu_critical);
p-&m_netInfo.send
= total_send - net_
p-&m_netInfo.recv
= total_recv - net_
p-&m_netInfo.total
= p-&m_netInfo.send + p-&m_netInfo.
LeaveCriticalSection(&p-&m_cpu_critical);
}//no error
//更新进程信息;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
if( hProcessSnap == INVALID_HANDLE_VALUE )
return GetLastError();
pe32.dwSize = sizeof( PROCESSENTRY32 );
if( !Process32First( hProcessSnap, &pe32 ) )
CloseHandle( hProcessSnap );
// Must clean up the snapshot object!
return GetLastError();
EnterCriticalSection(&p-&m_cpu_critical);
p-&m_procInfo.clear();
LeaveCriticalSection(&p-&m_cpu_critical);
= OpenProcess(PROCESS_ALL_ACCESS/*PROCESS_QUERY_INFORMATION | PROCESS_VM_READ*/, FALSE, pe32.th32ProcessID );
if( hP == NULL )
GetProcessTimes(hP,&creatTime,&exitTime,&procKernelTime,&procUserTime);
GetSystemTimeAsFileTime(&sysTime);
for(int i=0;i & procTimeInfo.size();i++)
if(procTimeInfo[i].pid == pe32.th32ProcessID)
//进程运行的总时间
= p-&CompareFileTime( procTimeInfo[i].kernelTime, procKernelTime);
= p-&CompareFileTime(procTimeInfo[i].userTime, procUserTime);
//已用系统时间
__int64 sysProc
= p-&CompareFileTime(procTimeInfo[i].lastSysTime,sysTime);
double cpu
= (((double)(k + u)*100)/sysProc/processorCount + 0.50001);
PROCESS_MEMORY_COUNTERS_EX
= sizeof(pmc);
GetProcessMemoryInfo(hP,(PROCESS_MEMORY_COUNTERS*)(&pmc),sizeof(pmc));
sys_process_
tmp.cpuUsage
tmp.memUsage
= pmc.PrivateUsage/1024;
= std::string(pe32.szExeFile);
= (int)pe32.th32ProcessID;
EnterCriticalSection(&p-&m_cpu_critical);
p-&m_procInfo.push_back(tmp);
LeaveCriticalSection(&p-&m_cpu_critical);
procTimeInfo[i].kernelTime
= procKernelT
procTimeInfo[i].userTime
= procUserT
procTimeInfo[i].lastSysTime = sysT
if(newProc)
process_time_info
= OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID );
if( hP == NULL )
procTime.pid
= (int)pe32.th32ProcessID;
procTime.lastSysTime
procTime.kernelTime
= procKernelT
procTime.userTime
= procUserT
CloseHandle(hP2);
CloseHandle(hP);
} while(Process32Next( hProcessSnap, &pe32));
CloseHandle( hProcessSnap );
if (pIfTable != NULL) {
FREE(pIfTable);
pIfTable = NULL;
EnterCriticalSection(&p-&m_cpu_critical);
if(p-&m_cpuUsage & 100)
p-&m_cpuUsage = 100;
if(p-&m_cpuUsage & 0)
p-&m_cpuUsage = 1;
LeaveCriticalSection(&p-&m_cpu_critical);
return DWORD(p-&m_cpuUsage);
WinSystemInfo::WinSystemInfo(void)
InitializeCriticalSection(&m_cpu_critical);
m_hCpuCountThread
m_cpuUsage
m_totalDiskSpace
initialize();
WinSystemInfo::~WinSystemInfo(void)
DeleteCriticalSection(&m_cpu_critical);
if(m_hCpuCountThread != NULL)
CloseHandle(m_hCpuCountThread);
void WinSystemInfo::initialize()
if(m_hCpuCountThread == NULL)
SECURITY_ATTRIBUTES
sa.bInheritHandle
sa.nLength
= sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
m_hCpuCountThread = CreateThread(&sa,0,CountCpuUsage,this,0,NULL);
int WinSystemInfo::getDrivesInfo(std::vector&DiskInfo&& drives,ULONGLONG& totalSpace, ULONGLONG& totalFreeSpace)
BOOL b_flag
ULARGE_INTEGER FreeAvailable,TotalNum,TotalFreeN
totalSpace
totalFreeSpace
ULONGLONG totalSpaceTmp
ULONGLONG totalFreeSpaceTmp = 0;
for( name = 'A';name &= 'Z';name++ )
char diskname[16]
sprintf(diskname,"%c:",name);
= GetDiskFreeSpaceEx(diskname ,&FreeAvailable,&TotalNum,&TotalFreeNum );
if( b_flag )
if(m_totalDiskSpace == 0)
totalSpaceTmp
= (int)(TotalNum.QuadPart/());
totalSpace
+= totalSpaceT
totalFreeSpaceTmp = (int)(FreeAvailable.QuadPart/());
totalFreeSpace
+= totalFreeSpaceT
= std::string(diskname);;
disk.total
= totalSpaceT
= totalFreeSpaceT
drives.push_back(disk);
if(m_totalDiskSpace == 0)
m_totalDiskSpace = totalS
totalSpace = m_totalDiskS
return drives.size();
int WinSystemInfo::getDiskAvailable()
std::vector&DiskInfo&
ULONGLONG totalSpace,totalFreeS
getDrivesInfo(tmp,totalSpace,totalFreeSpace);
return (int)((totalSpace - totalFreeSpace)*100/totalSpace);
void WinSystemInfo::GetMemInfo(sys_mem_info& info)
//mem status info
MEMORYSTATUSEX
mymem.dwLength
= sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&mymem);
memset(&info,0,sizeof(info));
info.total
= (mymem.ullTotalPhys)/;
= (mymem.ullAvailPhys)/;
__int64 WinSystemInfo::CompareFileTime (const FILETIME& time1,const FILETIME& time2 )
__int64 a = time1.dwHighDateTime && 16 && 16;
a |= time1.dwLowDateT
__int64 b = time2.dwHighDateTime && 16 && 16;
b |= time2.dwLowDateT
double WinSystemInfo::GetCpuInfo()
EnterCriticalSection(&m_cpu_critical);
tmp = m_cpuU
LeaveCriticalSection(&m_cpu_critical);
sys_net_info WinSystemInfo::GetNetInfo()
sys_net_info netI
EnterCriticalSection(&m_cpu_critical);
netInfo.recv
= m_netInfo.
netInfo.send
= m_netInfo.
netInfo.total
= m_netInfo.
LeaveCriticalSection(&m_cpu_critical);
return netI
void WinSystemInfo::GetConnInfo(std::vector&SysNetConnInfo&& conns)
MIB_TCPTABLE*
ptTables = NULL;
MIB_UDPTABLE*
puTables = NULL;
#if WINVER &= 0x0600 //0x0600是vista的版本号
MIB_TCP6TABLE*
pt6Tables = NULL;
MIB_UDP6TABLE*
pu6Tables = NULL;
if(ERROR_INSUFFICIENT_BUFFER == (retVal = GetExtendedTcpTable(ptTables,&size,FALSE,AF_INET,TCP_TABLE_BASIC_ALL,NULL)))
if(ptTables != NULL)
delete ptT
ptTables = 0;
ptTables = new MIB_TCPTABLE[size];
if(ptTables != NULL)
if(NO_ERROR !=(retVal =GetExtendedTcpTable(ptTables,&size,FALSE,AF_INET,TCP_TABLE_BASIC_ALL,NULL)))
//get tcp connections
if(retVal == NO_ERROR){
for(DWORD i =0; i & ptTables-&dwNumE i++)
SysNetConnI
in_addr n1,n2;
n1.S_un.S_addr = (u_long)ptTables-&table[i].dwLocalA
n2.S_un.S_addr = (u_long)ptTables-&table[i].dwRemoteA
= int(id++);
tmp.localAddr
= std::string(inet_ntoa(n1));
tmp.localPort
= ptTables-&table[i].dwLocalP
tmp.remoteAddr
= std::string(inet_ntoa(n2));
tmp.remotePort
= ptTables-&table[i].dwRemoteP
tmp.protocol
= ptTables-&table[i].S
tmp.ipInfo.tcpInfo.dwState
= int(id++);
tmp.ipInfo.tcpInfo.State
= ptTables-&table[i].S
tmp.ipInfo.tcpInfo.dwLocalAddr
= ptTables-&table[i].dwLocalA
tmp.ipInfo.tcpInfo.dwLocalPort
= ptTables-&table[i].dwLocalP
tmp.ipInfo.tcpInfo.dwRemoteAddr
= ptTables-&table[i].dwRemoteA
tmp.ipInfo.tcpInfo.dwRemotePort
= ptTables-&table[i].dwRemoteP
tmp.ipInfo.tcpInfo.dwState
= ptTables-&table[i].dwS
conns.push_back(tmp);
if(ptTables != NULL)
delete ptT
ptTables = NULL;
//get udp connections
if(ERROR_INSUFFICIENT_BUFFER == (retVal =GetExtendedUdpTable(puTables,&size,FALSE,AF_INET,UDP_TABLE_BASIC,NULL)))
if(puTables != NULL)
delete puT
puTables = 0;
puTables = new MIB_UDPTABLE[size];
if(puTables != NULL)
if(NO_ERROR != (retVal =GetExtendedUdpTable(puTables,&size,FALSE,AF_INET,UDP_TABLE_BASIC,NULL)))
if(retVal == NO_ERROR){
for(DWORD i =0; i & puTables-&dwNumE i++)
SysNetConnI
in_addr n1;
n1.S_un.S_addr = (u_long)puTables-&table[i].dwLocalA
= int(id++);
tmp.localAddr
= std::string(inet_ntoa(n1));
tmp.localPort
= puTables-&table[i].dwLocalP
tmp.remoteAddr
tmp.remotePort
tmp.protocol
= int(id++);
tmp.ipInfo.udpInfo.dwLocalAddr
= puTables-&table[i].dwLocalA
tmp.ipInfo.udpInfo.dwLocalPort
= puTables-&table[i].dwLocalP
conns.push_back(tmp);
if(puTables != NULL)
delete puT
puTables = NULL;
#if WINVER &= 0x0600 //0x0600是vista的版本号
if(ERROR_INSUFFICIENT_BUFFER == (retVal = GetExtendedTcpTable(pt6Tables,&size,FALSE,AF_INET6,TCP_TABLE_BASIC_ALL,NULL)))
if(pt6Tables != NULL)
delete pt6T
pt6Tables = 0;
pt6Tables = new MIB_TCP6TABLE[size];
if(pt6Tables != NULL)
if(NO_ERROR != (retVal =GetExtendedTcpTable(pt6Tables,&size,FALSE,AF_INET6,TCP_TABLE_BASIC_ALL,NULL)))
//get tcp6 connections
if(retVal == NO_ERROR)
for(DWORD i =0; i & pt6Tables-&dwNumE i++)
SysNetConnI
char in1[64] = {'\0'};
char in2[64] = {'\0'};
sprintf(in1,"%4x:%4x:%4x:%4x:%4x:%4x:%4x:%4x",
pt6Tables-&table[i].LocalAddr.u.Word[0],
pt6Tables-&table[i].LocalAddr.u.Word[1],
pt6Tables-&table[i].LocalAddr.u.Word[2],
pt6Tables-&table[i].LocalAddr.u.Word[3],
pt6Tables-&table[i].LocalAddr.u.Word[4],
pt6Tables-&table[i].LocalAddr.u.Word[5],
pt6Tables-&table[i].LocalAddr.u.Word[6],
pt6Tables-&table[i].LocalAddr.u.Word[7]
sprintf(in2,"%4x:%4x:%4x:%4x:%4x:%4x:%4x:%4x",
pt6Tables-&table[i].RemoteAddr.u.Word[0],
pt6Tables-&table[i].RemoteAddr.u.Word[1],
pt6Tables-&table[i].RemoteAddr.u.Word[2],
pt6Tables-&table[i].RemoteAddr.u.Word[3],
pt6Tables-&table[i].RemoteAddr.u.Word[4],
pt6Tables-&table[i].RemoteAddr.u.Word[5],
pt6Tables-&table[i].RemoteAddr.u.Word[6],
pt6Tables-&table[i].RemoteAddr.u.Word[7]
//InetNtop(AF_INET6,&(pt6Tables-&table[i].LocalAddr),in1,64);
//InetNtop(AF_INET6,&(pt6Tables-&table[i].RemoteAddr),in2,64);
= int(id++);
tmp.localAddr
= std::string(in1);
tmp.localPort
= pt6Tables-&table[i].dwLocalP
tmp.remoteAddr
= std::string(in2);
tmp.remotePort
= pt6Tables-&table[i].dwRemoteP
tmp.protocol
= pt6Tables-&table[i].S
//tmp.ipInfo.tcp6Info.dwState
= int(id++);
tmp.ipInfo.tcp6Info.State
= pt6Tables-&table[i].S
tmp.ipInfo.tcp6Info.LocalAddr
= pt6Tables-&table[i].LocalA
tmp.ipInfo.tcp6Info.dwLocalScopeId
= pt6Tables-&table[i].dwLocalScopeId;
tmp.ipInfo.tcp6Info.dwLocalPort
= pt6Tables-&table[i].dwLocalP
tmp.ipInfo.tcp6Info.RemoteAddr
= pt6Tables-&table[i].RemoteA
tmp.ipInfo.tcp6Info.dwRemoteScopeId = pt6Tables-&table[i].dwRemoteScopeId;
tmp.ipInfo.tcp6Info.dwRemotePort
= pt6Tables-&table[i].dwRemoteP
//tmp.ipInfo.tcp6Info.dwState
= pt6Tables-&table[i].dwS
conns.push_back(tmp);
if(pu6Tables != NULL)
delete pt6T
pt6Tables = NULL;
//get udp6 connections
if(ERROR_INSUFFICIENT_BUFFER == (retVal =GetExtendedUdpTable(pu6Tables,&size,FALSE,AF_INET6,UDP_TABLE_BASIC,NULL)))
if(pu6Tables != NULL)
delete pu6T
pu6Tables = 0;
pu6Tables = new MIB_UDP6TABLE[size];
if(pu6Tables != NULL)
if(NO_ERROR != (retVal =GetExtendedUdpTable(pu6Tables,&size,FALSE,AF_INET6,UDP_TABLE_BASIC,NULL)))
if(retVal == NO_ERROR){
for(DWORD i =0; i & pu6Tables-&dwNumE i++)
SysNetConnI
char in1[64] = {'\0'};
sprintf(in1,"%4x:%4x:%4x:%4x:%4x:%4x:%4x:%4x",
pu6Tables-&table[i].dwLocalAddr.u.Word[0],
pu6Tables-&table[i].dwLocalAddr.u.Word[1],
pu6Tables-&table[i].dwLocalAddr.u.Word[2],
pu6Tables-&table[i].dwLocalAddr.u.Word[3],
pu6Tables-&table[i].dwLocalAddr.u.Word[4],
pu6Tables-&table[i].dwLocalAddr.u.Word[5],
pu6Tables-&table[i].dwLocalAddr.u.Word[6],
pu6Tables-&table[i].dwLocalAddr.u.Word[7]
//InetNtop(AF_INET6,&(pt6Tables-&table[i].LocalAddr),in1,64);
= int(id++);
tmp.localAddr
= std::string(in1);
tmp.localPort
= pu6Tables-&table[i].dwLocalP
tmp.remoteAddr
tmp.remotePort
tmp.protocol
= int(id++);
tmp.ipInfo.udp6Info.dwLocalAddr
= pu6Tables-&table[i].dwLocalA
tmp.ipInfo.udp6Info.dwLocalPort
= pu6Tables-&table[i].dwLocalP
tmp.ipInfo.udp6Info.dwLocalScopeId
= pu6Tables-&table[i].dwLocalScopeId;
conns.push_back(tmp);
if(pu6Tables != NULL)
delete pu6T
pu6Tables = 0;
void WinSystemInfo::GetProcInfo(std::vector&sys_process_info&& procInfo)
EnterCriticalSection(&m_cpu_critical);
LeaveCriticalSection(&m_cpu_critical);
int WinSystemInfo::Get_processor_number()
SYSTEM_INFO
GetSystemInfo(&info);
return (int)info.dwNumberOfP
了这篇文章
类别:┆阅读(0)┆评论(0)
17:33:16 11:06:05 11:28:30 10:51:37 23:07:30 20:05:05 20:07:17

我要回帖

更多关于 批处理获取内存使用率 的文章

 

随机推荐