ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/sys/times.h
......
/* Structure describing CPU time used by a process and its children. */
struct tms
{
clock_t tms_utime; /* User CPU time. */
clock_t tms_stime; /* System CPU time. */
clock_t tms_cutime; /* User CPU time of dead children. */
clock_t tms_cstime; /* System CPU time of dead children. */
};
/* Store the CPU time used by this process and all its
dead children (and their dead children) in BUFFER.
Return the elapsed real time, or (clock_t) -1 for errors.
All times are in CLK_TCKths of a second. */
extern clock_t times (struct tms *__buffer) __THROW;
......
2. Example
times.c:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/times.h>
void pr_times(clock_t real, struct tms *tmstart, struct tms *tmend)
{
static long clktck = 0;
// Get the constant: number of clock tick per second
if(clktck == 0) {
if((clktck = sysconf(_SC_CLK_TCK)) < 0) {
printf("sysconf Error!\n");
exit(3);
}
}
printf(" real: %7.2f\n", real / (double)clktck);
printf(" user: %7.2f\n", (tmend->tms_utime - tmstart->tms_utime) / (double)clktck);
printf(" sys: %7.2f\n", (tmend->tms_stime - tmstart->tms_stime) / (double)clktck);
printf("child user: %7.2f\n", (tmend->tms_cutime - tmstart->tms_cutime) / (double)clktck);
printf("child sys: %7.2f\n", (tmend->tms_cstime - tmstart->tms_cstime) / (double)clktck);
}
void do_cmd(char *cmd)
{
struct tms tmstart, tmend;
clock_t start ,end;
int status;
// Retrieve the current time information
printf("\ncommand: %s\n", cmd);
if((start = times(&tmstart)) == -1) {
printf("times error!\n");
exit(1);
}
// Run the command
if((status = system(cmd)) < 0) {
printf("system error!\n");
exit(2);
}
// Retrieve the time information after running the command
if((end = times(&tmend)) == -1) {
printf("times error!\n");
exit(1);
}
pr_times(end-start, &tmstart, &tmend);
}
int main(int argc, char* argv[])
{
int i;
setbuf(stdout, NULL);
for(i=1; i < argc; i++) {
do_cmd(argv[i]);
}
exit(0);
}
shell:
ubuntu@ip-172-31-23-227:~$ ./times.out "sleep 5"
command: sleep 5
real: 5.00
user: 0.00
sys: 0.00
child user: 0.00
child sys: 0.00
No comments:
Post a Comment