sbase

suckless unix tools
git clone git://git.suckless.org/sbase
Log | Files | Refs | README | LICENSE

time.c (1369B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <sys/times.h>
      3 #include <sys/wait.h>
      4 
      5 #include <errno.h>
      6 #include <stdio.h>
      7 #include <unistd.h>
      8 
      9 #include "util.h"
     10 
     11 static void
     12 usage(void)
     13 {
     14 	eprintf("usage: %s [-p] cmd [arg ...]\n", argv0);
     15 }
     16 
     17 int
     18 main(int argc, char *argv[])
     19 {
     20 	pid_t pid;
     21 	struct tms tms; /* user and sys times */
     22 	clock_t r0, r1; /* real time */
     23 	long ticks;     /* per second */
     24 	int status, savederrno, ret = 0;
     25 
     26 	ARGBEGIN {
     27 	case 'p':
     28 		break;
     29 	default:
     30 		usage();
     31 	} ARGEND
     32 
     33 	if (!argc)
     34 		usage();
     35 
     36 	if ((ticks = sysconf(_SC_CLK_TCK)) <= 0)
     37 		eprintf("sysconf _SC_CLK_TCK:");
     38 
     39 	if ((r0 = times(&tms)) == (clock_t)-1)
     40 		eprintf("times:");
     41 
     42 	switch ((pid = fork())) {
     43 	case -1:
     44 		eprintf("fork:");
     45 	case 0:
     46 		execvp(argv[0], argv);
     47 		savederrno = errno;
     48 		weprintf("execvp %s:", argv[0]);
     49 		_exit(126 + (savederrno == ENOENT));
     50 	default:
     51 		break;
     52 	}
     53 	waitpid(pid, &status, 0);
     54 
     55 	if ((r1 = times(&tms)) == (clock_t)-1)
     56 		eprintf("times:");
     57 
     58 	if (WIFSIGNALED(status)) {
     59 		fprintf(stderr, "Command terminated by signal %d\n",
     60 		        WTERMSIG(status));
     61 		ret = 128 + WTERMSIG(status);
     62 	}
     63 
     64 	fprintf(stderr, "real %f\nuser %f\nsys %f\n",
     65 	        (r1 - r0)      / (double)ticks,
     66 	        tms.tms_cutime / (double)ticks,
     67 	        tms.tms_cstime / (double)ticks);
     68 
     69 	if (WIFEXITED(status))
     70 		ret = WEXITSTATUS(status);
     71 
     72 	return ret;
     73 }