Linux下评估程序运行时间及内存占用情况的简便方法
Sason@CSDN
从一篇英文论文中看到用于简易评估程序运行时间及内存占用情况的方法,查找资料后记录如下。
1.评估程序运行时间:
Linux下进行C程序开发时,可使用getrusage()函数进行程序运行时间的简易评估。
使用usage.ru_utime进行用户CPU时间(user CPU time)评估,对于系统CPU时间(system CPU time)评估使用usage.ru_stime.
如果程序运行于内核模式(kernel mode),使用ru_stime, 否则使用ru_utime.
getrusage()函数的说明:http://man7.org/linux/man-pages/man2/getrusage.2.html
StackOverFlow的讨论:http://stackoverflow.com/questions/10509660/getting-getrusage-to-measure-system-time-in-c
代码示例:
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <stdio.h>
int main() {
struct rusage usage;
struct timeval start, end;
int i, j, k = 0;
getrusage(RUSAGE_SELF, &usage);
start = usage.ru_utime; //usage.ru_stime
for (i = 0; i < 10000; i++) {
/* Double loop for more interesting results. */
for (j = 0; j < 10000; j++) {
k += 20;
}
}
getrusage(RUSAGE_SELF, &usage);
end = usage.ru_utime; //usage.ru_stime
printf("Started at: %ld.%lds\n", start.tv_sec, start.tv_usec);
printf("Ended at: %ld.%lds\n", end.tv_sec, end.tv_usec);
return 0;
}
2. 评估内存占用情况:
察看/proc/[PID]/statm, 其中[PID]是进程的PID号.
推荐阅读:http://elinux.org/Runtime_Memory_Measurement
来自http://www.lindevdoc.org/wiki//proc/pid/statm的解释:
The /proc/pid/statm file describes the memory usage of a process with the specified PID.
It is a single-line text file with following entries separated by whitespace:
Total process size (like VmSize in /proc/pid/status)
Resident set size (like VmRSS in /proc/pid/status)
Number of shared pages
Number of code pages, not including shared libraries[1]
Currently unused and always 0 (used to be number of library pages before kernel 2.6)
Number of data and stack pages together[2]
Currently unused and always 0 (used to be number of dirty pages before kernel 2.6)
这些输出参数的解释:
Size (total pages) 任务虚拟地址空间的大小 VmSize/4
Resident(pages) 应用程序正在使用的物理内存的大小 VmRSS/4
Shared(pages) 共享页数 0
Trs(pages) 程序所拥有的可执行虚拟内存的大小 VmExe/4
Lrs(pages) 被映像到任务的虚拟内存空间的库的大小 VmLib/4
Drs(pages) 程序数据段和用户态的栈的大小 (VmData+ VmStk )4
dt(pages) 脏页数量
增加上个例子中的循环次数,运行后,察看内存占用情况:
admin@admin:~$ cat /proc/3292/statm
501 70 57 1 0 41 0
admin@admin:~$ cat /proc/3292/status
Name: measuretime
State: R (running)
Tgid: 3292
Pid: 3292
PPid: 2693
TracerPid: 0
Uid: 1000 1000 1000 1000
Gid: 1000 1000 1000 1000
FDSize: 256
Groups: 4 24 27 30 46 109 124 1000
VmPeak: 2108 kB
VmSize: 2004 kB //等于total pages * 4 = 501 * 4 = 2004
VmLck: 0 kB
VmPin: 0 kB
VmHWM: 280 kB
VmRSS: 280 kB //等于resident pages * 4 = 70 * 4 = 280
VmData: 28 kB //VmData + VmStk = 164 164 / 4 = 41 (Drs pages)
VmStk: 136 kB
VmExe: 4 kB
VmLib: 1804 kB
VmPTE: 12 kB
VmSwap: 0 kB
Threads: 1
SigQ: 0/15994
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: ffffffffffffffff
Cpus_allowed: f
Cpus_allowed_list: 0-3
Mems_allowed: 1
Mems_allowed_list: 0
voluntary_ctxt_switches: 1
nonvoluntary_ctxt_switches: 41173