/* CPU & WALL time usage timer routine */
/* returns -1 (error), 0 (ok) */
#include <stdio.h>
#include <unistd.h>
#include <sys/times.h>
#include <sys/time.h>
int timer(int option)
{
static struct tms begin_cpu, end_cpu;
static struct timeval begin_wall, end_wall;
long clk_tick;
switch (option) {
case 0 :
if (gettimeofday(&begin_wall, NULL) == -1)
err_sys("gettimeofday");
if (times(&begin_cpu) == -1)
err_sys("times");
return(0);
case 1 :
if (gettimeofday(&end_wall, NULL) == -1)
err_sys("gettimeofday");
if (times(&end_cpu) == -1)
err_sys("times");
if ((clk_tick = sysconf(_SC_CLK_TCK)) == -1)
err_sys("sysconf");
fprintf(stderr, "wall time = %ld sec\n\n",
end_wall.tv_sec - begin_wall.tv_sec);
fprintf(stderr, "cpu time = %.2f sec\n",
((end_cpu.tms_utime + end_cpu.tms_stime) -
(begin_cpu.tms_utime + begin_cpu.tms_stime)) /
(double) clk_tick);
fprintf(stderr, " user = \t %.2f sec\n",
(end_cpu.tms_utime - begin_cpu.tms_utime) /
(double) clk_tick);
fprintf(stderr, " system = \t %.2f sec\n\n",
(end_cpu.tms_stime - begin_cpu.tms_stime) /
(double) clk_tick);
fprintf(stderr, "cpu time = %.2f sec (children)\n",
((end_cpu.tms_cutime + end_cpu.tms_cstime) -
(begin_cpu.tms_cutime + begin_cpu.tms_cstime)) /
(double) clk_tick);
fprintf(stderr, " user = \t %.2f sec\n",
(end_cpu.tms_cutime - begin_cpu.tms_cutime) /
(double) clk_tick);
fprintf(stderr, " system = \t %.2f sec\n",
(end_cpu.tms_cstime - begin_cpu.tms_cstime) /
(double) clk_tick);
return(0);
default :
fprintf(stderr, "timer: bad option (%d)\n", option);
return(-1);
}
}