当打开Windows任务管理器时,就会看到每个进程使用内存的分布情况,往往会发现有一些进程占用大量的内存,这种情况也是一种异常情况,可以作为是否恶意软件的标志之一。下面就来使用API函数GetProcessMemoryInfo来获取内存的使用情况。

函数GetProcessMemoryInfo声明如下:

BOOL WINAPI GetProcessMemoryInfo (

HANDLE Process,

PPROCESS_MEMORY_COUNTERS ppsmemCounters,

DWORD cb

);

Process是获取内存使用情况的进程句柄。

ppsmemCounters是返回内存使用情况的结构。

cb是结构的大小。

使用函数GetProcessMemoryInfo获取程序当前内存使用量的步骤如下:

1.在程序中添加pragma comment(lib,"Psapi.lib"),将Psapi.lib包含进去,或者通过在工程属性中添加Psapi.lib

2.在系统中包含Psapi.h文件;

3.在需要查看内存的代码处添加如下代码:

HANDLE handle = GetCurrentProcess();

PROCESS_MEMORY_COUNTERS pmc;

GetProcessMemoryInfo(handle,&pmc, sizeof(pmc));

printf("%d\r\n",pmc.WorkingSetSize);

其中pmc.WorkingSetSize就是程序在当前代码处的内存使用量。

另外,handle也可用下面对象代替,

DWORD dwprcess;

HANDLE hprocess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VN_READ, FALSE,dwprocess);

 

Function: Contains the memory statistics for aprocess.

Syntax:

typedef struct _PROCESS_MEMORY_COUNTERS {

DWORD cb;

DWORD PageFaultCount;

SIZE_T PeakWorkingSetSize;

SIZE_T WorkingSetSize;

SIZE_T QuotaPeakPagedPoolUsage;

SIZE_T QuotaPagedPoolUsage;

SIZE_T QuotaPeakNonPagedPoolUsage;

SIZE_T QuotaNonPagedPoolUsage;

SIZE_T PagefileUsage;

SIZE_T PeakPagefileUsage;

} PROCESS_MEMORY_COUNTERS, *PPROCESS_MEMORY_COUNTERS;

 

cb -- Size of the structure, in bytes.

PageFaultCount -- Number of page faults. 

PeakWorkingSetSize -- Peak working set size, in bytes. // 峰值内存使用

WorkingSetSize -- Current working set size, inbytes.  // 内存使用

QuotaPeakPagedPoolUsage -- Peak paged pool usage, in bytes.

QuotaPagedPoolUsage -- Current paged pool usage, inbytes.

QuotaPeakNonPagedPoolUsage -- Peak nonpaged pool usage, inbytes.

QuotaNonPagedPoolUsage -- Current nonpaged pool usage, inbytes.

PagefileUsage -- Current space allocated for thepagefile, in bytes.Those pages may or may not be in memory. // 虚拟内存使用

PeakPagefileUsage -- Peak space allocated for thepagefile, in bytes. // 峰值虚拟内存使用

 

相关链接:https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process

 




Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐