#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/resource.h>
voidprint_rusage(
const char * where)
{
struct rusage used;
getrusage(RUSAGE_SELF, &used);
printf("In %s:\n", where);
printf("user cpu time: %ld(ms)\n",
used.ru_utime.tv_sec * 1000 + used.ru_utime.tv_usec / 1000);
printf("sys cpu time: %ld(ms)\n",
used.ru_stime.tv_sec * 1000 + used.ru_stime.tv_usec / 1000);
printf("soft page faults: %ld\n", used.ru_minflt);
printf("\n");
}
voidconsume_rusage()
{
int i, j, k;
char * s = NULL;
/* about 3 seconds user cpu time */ for (i = 0; i < 1000; ++i)
for (j = 0; j < 1000; ++j)
for (k = 0; k < 1000; ++k)
i / (j + 1) * k;
/* 1000 soft page faults */ k = 4096 * 1000;
s = (
char *)malloc(k);
for (i = 0; i < k; ++i)
s[i] = 'a';
}
intmain(
int argc,
char *argv[])
{
consume_rusage();
print_rusage("parent process");
if (fork() == 0) {
print_rusage("child process, after fork");
printf("consuming resource
![](http://www.cppblog.com/Images/dot.gif)
\n\n");
consume_rusage();
print_rusage("child process, before execve");
printf("excl child program now
![](http://www.cppblog.com/Images/dot.gif)
\n\n");
execl("./child", "./child", (
void *)0);
}
wait(NULL);
return 0;
}