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
|
//! What instrumentation costs, measured on a target: runs PROGRAM and prints
//! one line, its wall time in milliseconds and the events it emitted by kind.
//!
//! bench PROGRAM ARGS with a ring, drained and counted, nothing recorded
//! bench --untraced PROGRAM ARGS with no ring: the calls return at once
//! bench --step PROGRAM ARGS held at each `line` by the ring's stop mask, resumed at once
//!
//! llvm/bench.sh makes the tables from it.
const std = @import("std");
const linux = std.os.linux;
const zt = @import("ztrace");
var counts: [64]u64 = @splat(0);
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const args = try init.minimal.args.toSlice(arena);
const mode: enum { ring, untraced, step } = if (args.len > 1 and std.mem.eql(u8, args[1], "--untraced")) .untraced else if (args.len > 1 and std.mem.eql(u8, args[1], "--step")) .step else .ring;
const rest = args[@as(usize, 1) + @intFromBool(mode != .ring) ..];
if (rest.len == 0) return error.Usage;
const argv = try arena.allocSentinel(?[*:0]const u8, rest.len, null);
for (argv, rest) |*dst, s| dst.* = s.ptr;
const env = init.minimal.environ.block.slice;
const start = zt.event.now();
if (mode == .untraced) {
const pid = linux.fork();
if (pid == 0) {
_ = linux.execve(argv[0].?, argv.ptr, env.ptr);
linux.exit_group(127);
}
var status: u32 = 0;
_ = linux.waitpid(@intCast(pid), @ptrCast(&status), 0);
} else {
var session = try zt.host.Session.spawn(arena, argv[0].?, argv.ptr, env, .{ .stop_mask = if (mode == .step) zt.Kind.line.bit() else 0 });
defer session.close();
const ring = &session.ring;
// Step mode answers each stop at once. Otherwise the consumer drains
// what there is and sleeps a moment, never on the ring's futex: so
// the producer pays neither a wake nor for a cache line the consumer
// keeps taking, and the time is the cost of producing.
while (true) {
const rec = ring.peek() orelse {
if (session.exit_code != null) break;
var status: u32 = 0;
if (linux.waitpid(session.pid, @ptrCast(&status), linux.W.NOHANG) != 0) {
session.exit_code = 0;
} else if (mode == .step) std.atomic.spinLoopHint() else _ = linux.nanosleep(&.{ .sec = 0, .nsec = 200_000 }, null);
continue;
};
const kind = rec.ev.kind;
counts[@intFromEnum(kind)] += 1;
ring.advance(rec);
if (mode == .step and kind == .line) ring.resumeAll();
}
}
const ms = @as(f64, @floatFromInt(zt.event.now() - start)) / 1e6;
var buf: [1024]u8 = undefined;
var out = std.Io.File.stdout().writer(init.io, &buf);
const w = &out.interface;
var total: u64 = 0;
for (counts) |n| total += n;
try w.print("{d:.2} {d}", .{ ms, total });
for (counts, 0..) |n, kind| {
if (n > 0) try w.print(" {t}={d}", .{ @as(zt.Kind, @enumFromInt(kind)), n });
}
try w.print("\n", .{});
try w.flush();
}
|