aboutsummaryrefslogtreecommitdiffstats
path: root/shell_cmds/systime/systime.c
blob: 555fc6afbe57b8c11e202d171d4bfedda6841f58 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/*
 * Copyright (c) 2012 Apple Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include <mach/mach.h>
#include <err.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libproc.h>
#include <mach/mach_time.h>

#include <libiosexec.h>

static void usage(void);
static void do_print(void);
static void do_difftime(bool usepercent, uint64_t *olduser, uint64_t *oldsystem, uint64_t *oldidle);
static void do_piddifftime(bool userpercent, int pid, uint64_t *old_pid_user, uint64_t *old_pid_system, uint64_t *old_pid_time);
static kern_return_t get_processor_time(uint64_t *user, uint64_t *sys, uint64_t *idle);
static kern_return_t get_processor_count(int *ncpu);
static mach_timebase_info_data_t timebase_info;

int
main(int argc, char *argv[])
{
	int ch;
	const char *optu = NULL;
	const char *opts = NULL;
	const char *opti = NULL;
	const char *tpid = NULL;
	const char *opt_sleep_time = NULL;
	int sleep_time = 1;
	int target_pid;
	bool systemwide_time = false;
	int pid;
	int status;
	uint64_t olduser, oldsystem, oldidle;
	uint64_t old_pid_time;
	uint64_t old_pid_user, old_pid_system;
	kern_return_t kret;
	bool usepercent = false;
	bool recurring = false;

	while ((ch = getopt(argc, argv, "PrT:t:pu:s:i:")) != -1) {
		switch (ch) {
		case 'P':
			usepercent = true;
			break;
		case 'r':
			recurring = true;
			break;
		case 't':
			opt_sleep_time = optarg;
			break;
		case 'T':
			tpid = optarg;
			break;
		case 'p':
			systemwide_time = true;
			break;
		case 'u':
			optu = optarg;
			break;
		case 's':
			opts = optarg;
			break;
		case 'i':
			opti = optarg;
			break;
		case '?':
		default:
			usage();
		}
	}

	mach_timebase_info(&timebase_info);

	if (opt_sleep_time) {
		char *endstr;
		sleep_time = (int)strtoul(opt_sleep_time, &endstr, 0);
		if (opt_sleep_time[0] == '\0' || endstr[0] != '\0')
			usage();
	}
	
	if (systemwide_time) {
		bool first_pass = true;
		olduser = oldsystem = oldidle = 0;

		if (recurring != true) {
			do_print();
			exit(0);
		}
		do {
			if (first_pass) {
				do_difftime(false, &olduser, &oldsystem, &oldidle);
				first_pass = false;
			} else {
				do_difftime(usepercent, &olduser, &oldsystem, &oldidle);
			}
			sleep(sleep_time);
		} while (recurring);

		exit(0);
	}


	if (tpid) {
		char *endstr;
		bool first_pass = true;

		target_pid = (int)strtoul(tpid, &endstr, 0);
		if (tpid[0] == '\0' || endstr[0] != '\0')
			usage();

		olduser = oldsystem = oldidle = 0;
		old_pid_user = old_pid_system = old_pid_time = 0;
		
		do {	
			if (first_pass) {
				do_difftime(false, &olduser, &oldsystem, &oldidle);
				do_piddifftime(false, target_pid, &old_pid_user, &old_pid_system, &old_pid_time);
				first_pass = false;
			} else {
				do_difftime(usepercent, &olduser, &oldsystem, &oldidle);
				do_piddifftime(usepercent, target_pid, &old_pid_user, &old_pid_system, &old_pid_time);
			}

			sleep(sleep_time);
		} while (recurring);
		exit(0);
	}

	if (optu || opts || opti) {
		char *endstr;

		if (!optu)
			usage();
		olduser = strtoull(optu, &endstr, 0);
		if (optu[0] == '\0' || endstr[0] != '\0')
			usage();

		if (!opts)
			usage();
		oldsystem = strtoull(opts, &endstr, 0);
		if (opts[0] == '\0' || endstr[0] != '\0')
			usage();

		if (!opti)
			usage();
		oldidle = strtoull(opti, &endstr, 0);
		if (opti[0] == '\0' || endstr[0] != '\0')
			usage();

		do_difftime(usepercent, &olduser, &oldsystem, &oldidle);
		exit(0);
	}

	argc -= optind;
	argv += optind;

	if (argc == 0)
		usage();

	do {
		kret = get_processor_time(&olduser, &oldsystem, &oldidle);
		if (kret)
			errx(1, "Error getting processor time: %s (%d)", mach_error_string(kret), kret);

		switch(pid = vfork()) {
			case -1:			/* error */
				perror("time");
				exit(1);
				/* NOTREACHED */
			case 0:				/* child */
				execvp(*argv, argv);
				perror(*argv);
				_exit((errno == ENOENT) ? 127 : 126);
				/* NOTREACHED */
		}

		/* parent */
		(void)signal(SIGINT, SIG_IGN);
		(void)signal(SIGQUIT, SIG_IGN);
		while (wait(&status) != pid);
		(void)signal(SIGINT, SIG_DFL);
		(void)signal(SIGQUIT, SIG_DFL);

		do_difftime(usepercent, &olduser, &oldsystem, &oldidle);

		sleep(sleep_time);
	} while (recurring);

	exit (WIFEXITED(status) ? WEXITSTATUS(status) : EXIT_FAILURE);

    return 0;
}

static void
usage(void)
{
	fprintf(stderr, "usage: systime [-P] [-r] [-t sleep_time] utility [argument ...]\n"
	                "       systime -p [-r] [-t sleep_time]\n"
	                "       systime [-P] -u user -s sys -i idle\n"
			"       systime [-P] [-r] [-t sleep_time] -T target_pid\n");
	exit(1);
}

static void
do_print(void)
{
	uint64_t user, system, idle;
	kern_return_t kret;

	kret = get_processor_time(&user, &system, &idle);
	if (kret)
		errx(1, "Error getting processor time: %s (%d)", mach_error_string(kret), kret);

	printf("systime_user=%llu\n",	user);
	printf("systime_sys=%llu\n",	system);
	printf("systime_idle=%llu\n",	idle);
}

static void
do_difftime(bool usepercent, uint64_t *olduser, uint64_t *oldsystem, uint64_t *oldidle)
{
	uint64_t user, system, idle;
	uint64_t userelapsed, systemelapsed, idleelapsed, totalelapsed;
	kern_return_t kret;

	kret = get_processor_time(&user, &system, &idle);
	if (kret)
		errx(1, "Error getting processor time: %s (%d)", mach_error_string(kret), kret);

	userelapsed = user - *olduser;
	systemelapsed = system - *oldsystem;
	idleelapsed = idle - *oldidle;
	totalelapsed = userelapsed + systemelapsed + idleelapsed;

	if (usepercent) {
		fprintf(stderr, "%1.02f%% user %1.02f%% sys %1.02f%% idle\n",
			   ((double)userelapsed * 100)/totalelapsed,
			   ((double)systemelapsed * 100)/totalelapsed,
			   ((double)idleelapsed * 100)/totalelapsed);
	} else {
		int ncpu;

		kret = get_processor_count(&ncpu);
		if (kret)
			errx(1, "Error getting processor count: %s (%d)", mach_error_string(kret), kret);

		fprintf(stderr, "%1.02f real %1.02f user %1.02f sys\n",
				((double)totalelapsed) / 1000 /* ms per sec */ / ncpu,
				((double)userelapsed) / 1000,
				((double)systemelapsed) / 1000);
	}
	*olduser = user;
	*oldsystem = system;
	*oldidle = idle;
}

static void
do_piddifftime(bool usepercent, int pid, uint64_t *old_pid_user, uint64_t *old_pid_system, uint64_t *old_pid_time)
{
	uint64_t pid_user, pid_system, pid_time;
	uint64_t userelapsed, systemelapsed, totalelapsed;
	struct proc_taskinfo info;
	int size;

	size = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &info, sizeof(info));
	if (size == PROC_PIDTASKINFO_SIZE) {
		pid_user = info.pti_total_user;
		pid_system = info.pti_total_system;
	} else {
		fprintf(stderr, "Error in proc_pidinfo(): %s",
				strerror(errno));
		exit(1);
	}

	pid_time = mach_absolute_time();

	userelapsed = pid_user - *old_pid_user;
	systemelapsed = pid_system - *old_pid_system;
	totalelapsed = pid_time - *old_pid_time;

	if (usepercent) {
		fprintf(stderr, "Pid %d: %1.02f%% user %1.02f%% sys\n",
			   pid,
			   ((double)userelapsed * 100)/totalelapsed,
			   ((double)systemelapsed * 100)/totalelapsed);
	} else {
		fprintf(stderr, "Pid %d: %1.02f user %1.02f sys\n",
				pid,
				(((double)userelapsed) * timebase_info.numer / timebase_info.denom) / 1000000000,
				(((double)systemelapsed) * timebase_info.numer / timebase_info.denom) / 1000000000);
	}

	*old_pid_user = pid_user;
	*old_pid_system = pid_system;
	*old_pid_time = pid_time;

}

static kern_return_t
get_processor_time(uint64_t *user, uint64_t *sys, uint64_t *idle)
{
	host_name_port_t	host;
	kern_return_t		kret;
	host_cpu_load_info_data_t	host_load;
	mach_msg_type_number_t	count;

	host = mach_host_self();

	count = HOST_CPU_LOAD_INFO_COUNT;

	kret = host_statistics(host, HOST_CPU_LOAD_INFO, (host_info_t)&host_load, &count);
	if (kret)
		return kret;

	*user = ((uint64_t)host_load.cpu_ticks[CPU_STATE_USER]) * 10 /* ms per tick */;
	*sys = ((uint64_t)host_load.cpu_ticks[CPU_STATE_SYSTEM]) * 10;
	*idle = ((uint64_t)host_load.cpu_ticks[CPU_STATE_IDLE]) * 10;

	return KERN_SUCCESS;
}

static kern_return_t
get_processor_count(int *ncpu)
{
	host_name_port_t	host;
	kern_return_t		kret;
	host_basic_info_data_t	hi;
	mach_msg_type_number_t	count;

	host = mach_host_self();

	count = HOST_BASIC_INFO_COUNT;

	kret = host_info(host, HOST_BASIC_INFO, (host_info_t)&hi, &count);
	if (kret)
		return kret;

	*ncpu = hi.avail_cpus;

	return KERN_SUCCESS;
}