Linux命令来检测程序的计算机资源使用情况 [英] Linux commands to detect the computer resource usage of a program
问题描述
假设有两个程序a.out
和b.out
做同样的事情:对元素进行排序. a.out
实现QuickSort
排序算法,这需要O(nlogn)
时间和O(logn)
内存,b.out
实现BubbleSort
排序算法,这要花费O(n^2)
时间和O(1)
内存.我想对这两种算法之间的时间和内存比较有一些直观的了解,因此,是否有任何Linux命令来测量程序运行后的时间和内存使用情况?
Suppose there are two programs a.out
and b.out
doing the same thing: sorting elements. a.out
implements a QuickSort
sorting algorithm, which takes O(nlogn)
time and O(logn)
memory, b.out
implements a BubbleSort
sorting algorithm, which takes O(n^2)
time and O(1)
memory. I want to gain some intuitive feelings of the time and memory comparison between these two algorithms, so is there any Linux command to measure the time and memory usage of a program after it is run ?
推荐答案
在程序上,我将使用getrusage()
,它允许您测量单个函数,并且比time
或top
更详细.例如:
Programatically, I would use getrusage()
, which allows you to measure single functions, and in a lot more detail than just time
or top
. For example:
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
struct rusage start;
struct rusage end;
getrusage (RUSAGE_SELF, &start); // get time at start
some_function (); // Function to measure
getrusage (RUSAGE_SELF, &end); // get time at end
printf ("System: %d usecs, User: %d usecs\n",
end.ru_stime.tv_usec - start.ru_stime.tv_usec,
end.ru_utime.tv_usec - start.ru_utime.tv_usec);
...
rusage
结构包含以下内容:
struct rusage {
struct timeval ru_utime; // user time used
struct timeval ru_stime; // system 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
long ru_majflt; // page faults
long ru_nswap; // swaps
long ru_inblock; // block input operations
long ru_oublock; // block output operations
long ru_msgsnd; // messages sent
long ru_msgrcv; // messages received
long ru_nsignals; // signals received
long ru_nvcsw; // voluntary context switches
long ru_nivcsw; // involuntary context switches
};
这篇关于Linux命令来检测程序的计算机资源使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!