-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcpuwatcher.d
69 lines (67 loc) · 1.78 KB
/
cpuwatcher.d
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
/+dub.sdl:
name "cpuwatcher"
dependency "resusage" path="../"
+/
import std.stdio;
import std.conv;
import std.getopt;
import std.process;
import core.thread;
import core.time;
import resusage.cpu;
int main(string[] args)
{
CPUWatcher cpuWatcher;
bool spawn;
uint rate = 3;
getopt(args, "spawn", "spawn process and watch its CPU usage", &spawn,
"rate", "how often to print current CPU usage (seconds)", &rate
);
Pid pid;
if (spawn) {
if (args.length <= 1) {
stderr.writeln("Expected command line to spawn");
return 1;
}
auto command = args[1..$];
version(Posix) {
auto devNull = File("/dev/null", "rw");
pid = spawnProcess(command, devNull, devNull, devNull);
} else {
pid = spawnProcess(command);
}
cpuWatcher = new ProcessCPUWatcher(pid.processID);
} else {
if (args.length < 2) {
cpuWatcher = new SystemCPUWatcher();
writeln("Watching system cpu");
} else {
string pidStr = args[1];
cpuWatcher = new ProcessCPUWatcher(to!int(pidStr));
writeln("Watching cpu for process ", pidStr);
}
}
while(true) {
Thread.sleep(dur!("seconds")(rate));
if (pid) {
auto result = tryWait(pid);
if (result.terminated) {
writeln("The spawned process exited");
return 0;
}
}
double percent;
try
{
percent = cpuWatcher.current();
}
catch(Exception e)
{
stderr.writefln("Couldn't get cputime: %s", e.msg);
break;
}
writefln("%s%%", percent);
stdout.flush();
}
return 0;
}