日期:2014-05-16 浏览次数:20906 次
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]