(开放供编辑和建议) 正如 Barmer 提到的,getrusage 返回以下内容(根据 man getrusage):-
struct rusage {
struct timeval ru_utime; /* user CPU time used */
struct timeval ru_stime; /* system CPU time used */
long ru_maxrss; /* maximum resident set size */
long ru_ixrss; /* integral shared memory size */
long ru_idrss; /* integral unshared data size */
long ru_isrss; /* integral unshared stack size */
long ru_minflt; /* page reclaims (soft page faults) */
long ru_majflt; /* page faults (hard page faults) */
long ru_nswap; /* swaps */
long ru_inblock; /* block input operations */
long ru_oublock; /* block output operations */
long ru_msgsnd; /* IPC messages sent */
long ru_msgrcv; /* IPC messages received */
long ru_nsignals; /* signals received */
long ru_nvcsw; /* voluntary context switches */
long ru_nivcsw; /* involuntary context switches */
};
要检查最大驻留集大小,您可以使用此程序:-
#include <sys/resource.h>
#include <stdio.h>
void print_memory_usage() {
struct rusage usage;
if (getrusage(RUSAGE_SELF, &usage) == 0) {
printf("Max Resident Set Size (KB): %ld\n", usage.ru_maxrss);
} else {
perror("getrusage");
}
}
int main() {
print_memory_usage();
return 0;
}
这里有关于虚拟内存的很好的介绍https://student.cs.uwaterloo.ca/~cs350/S21/notes/virtualmemory-2up.pdf 我们可以使用
sysconf
来计算页面大小和页面数量,这可以用于计算虚拟内存。
#include <unistd.h>
#include <stdio.h>
void print_virtual_memory_size() {
long page_size = sysconf(_SC_PAGESIZE);
long num_pages = sysconf(_SC_PHYS_PAGES);
if (page_size != -1 && num_pages != -1) {
printf("Virtual Memory Size (bytes): %ld\n", page_size * num_pages);
} else {
perror("sysconf");
}
}
int main() {
print_virtual_memory_size();
return 0;
}
(用户7860670评论中的回答)vmstat和/proc/PID/smaps是内存分析的好工具。