Have a look at the system call
getrusage(). If you use RUSAGE_SELF as the first parameter then the rusage struct is filled with process information about the current process. Then you need to process the timeval structures ru_utime and ru_stime. Each of these contain the user and system time used by the process. For example this prints the CPU time:
Code:
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
struct rusage process_usage;
getrusage(RUSAGE_SELF, &process_usage);
printf("CPU time: %ld.%06ld sec user, %ld.%06ld sec system\n",
process_usage.ru_utime.tv_sec, process_usage.ru_utime.tv_usec,
process_usage.ru_stime.tv_sec, process_usage.ru_stime.tv_usec
}
Also have a look at
alarm(). This will raise a SIGALRM which use can handled by setting a function to be called using
signal().
If you have the manual pages installed you can find out more with the command:
Code:
man [function name]
Finally I highly recommend the free book
Advanced Linux Programming. It details many of the techniques used to solve problems like the one you mentioned. It quite a read but its worth it.
Edit: Heres a sample program that will run for a minute and print CPU time at the end.
Code:
#include <signal.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
void timer_expired(int signal);
sig_atomic_t active;
int main(int argc, char *argv[]) {
signal(SIGALRM, &timer_expired);
//Sets the alarm to raise a SIGALRM in 60 seconds.
alarm(60);
active = 1;
fprintf(stdout, "Running ");
while (active) {
printf(".");
fflush(stdout);
sleep(1);
}
printf("\n");
struct rusage usage;
if (getrusage(RUSAGE_SELF, &usage) == -1) {
printf("Failed to get usage information.\n");
return 0;
}
printf("CPU time: %ld.%06ld sec user, %ld.%06ld sec system\n",
usage.ru_utime.tv_sec, usage.ru_utime.tv_usec,
usage.ru_utime.tv_sec, usage.ru_utime.tv_usec);
return 0;
}