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 ?
4 Answers
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);
...
The rusage struct contains the following:
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
};
Comments
Use time which will give you real, user and system times of the programs. e.g.
time ./a.out
The top command can be used for memory usage.
For getting time of the program, you can follow the following link. It shows how to use time command.
Get program execution time in the shell
For memory resources, please look at the following link for how to use top command in linux.
1 Comment
try time - time a simple command or give resource usage. The GNU version also reports memory usage:
/usr/bin/time --format="real\t%e\nuser\t%U\nsys\t%S\nmem:\t%M" -- ./a.out
3 Comments
/usr/bin. You need to specify path if you want this version to run. Otherwise shell version of time will be executed