forked from Sahnvour/zig-benchmark
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbench.zig
266 lines (230 loc) · 7.4 KB
/
bench.zig
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
const std = @import("std");
const TypeInfo = @import("builtin").TypeInfo;
const assert = std.debug.assert;
const time = std.time;
const warn = std.debug.warn;
const Timer = time.Timer;
const BenchFn = fn (*Context) void;
pub const Context = struct {
timer: Timer,
iter: u32,
count: u32,
state: State,
nanoseconds: u64,
const HeatingTime = time.second / 2;
const RunTime = time.second / 2;
const State = enum {
None,
Heating,
Running,
Finished,
};
pub fn init() Context {
return Context{ .timer = Timer.start() catch unreachable, .iter = 0, .count = 0, .state = .None, .nanoseconds = 0 };
}
pub fn run(self: *Context) bool {
switch (self.state) {
.None => {
self.state = .Heating;
self.timer.reset();
return true;
},
.Heating => {
self.count += 1;
const elapsed = self.timer.read();
if (elapsed >= HeatingTime) {
// Caches should be hot
self.count = @intCast(u32, RunTime / (HeatingTime / self.count));
self.state = .Running;
self.timer.reset();
}
return true;
},
.Running => {
if (self.iter < self.count) {
self.iter += 1;
return true;
} else {
self.nanoseconds = self.timer.read();
self.state = .Finished;
return false;
}
},
.Finished => unreachable,
}
}
pub fn startTimer(self: *Context) void {
self.timer.reset();
}
pub fn stopTimer(self: *Context) void {
const elapsed = self.timer.read();
self.nanoseconds += elapsed;
}
pub fn runExplicitTiming(self: *Context) bool {
switch (self.state) {
.None => {
self.state = .Heating;
return true;
},
.Heating => {
self.count += 1;
if (self.nanoseconds >= HeatingTime) {
// Caches should be hot
self.count = @intCast(u32, RunTime / (HeatingTime / self.count));
self.nanoseconds = 0;
self.state = .Running;
}
return true;
},
.Running => {
if (self.iter < self.count) {
self.iter += 1;
return true;
} else {
self.state = .Finished;
return false;
}
},
.Finished => unreachable,
}
}
pub fn averageTime(self: *Context, unit: u64) f32 {
assert(self.state == .Finished);
return @intToFloat(f32, self.nanoseconds / unit) / @intToFloat(f32, self.iter);
}
};
pub fn benchmark(name: comptime []const u8, f: BenchFn) void {
var ctx = Context.init();
@call(.{ .modifier = .never_inline }, f, .{&ctx});
var unit: u64 = undefined;
var unit_name: []const u8 = undefined;
const avg_time = ctx.averageTime(1);
assert(avg_time >= 0);
if (avg_time <= time.microsecond) {
unit = 1;
unit_name = "ns";
} else if (avg_time <= time.millisecond) {
unit = time.microsecond;
unit_name = "us";
} else {
unit = time.millisecond;
unit_name = "ms";
}
warn("{}: avg {d:.3}{} ({} iterations)\n", .{ name, ctx.averageTime(unit), unit_name, ctx.iter });
}
fn benchArgFn(comptime argType: type) type {
return fn (*Context, argType) void;
}
fn argTypeFromFn(comptime f: var) type {
comptime const F = @TypeOf(f);
if (@typeInfo(F) != .Fn) {
@compileError("Argument must be a function.");
}
const fnInfo = @typeInfo(F).Fn;
if (fnInfo.args.len != 2) {
@compileError("Only functions taking 1 argument are accepted.");
}
return fnInfo.args[1].arg_type.?;
}
pub fn benchmarkArgs(comptime name: []const u8, comptime f: var, comptime args: []const argTypeFromFn(f)) void {
inline for (args) |a| {
var ctx = Context.init();
comptime const options = std.builtin.CallOptions{ .modifier = .never_inline };
@call(options, f, .{ &ctx, a });
var unit: u64 = undefined;
var unit_name: []const u8 = undefined;
const avg_time = ctx.averageTime(1);
assert(avg_time >= 0);
if (avg_time <= time.microsecond) {
unit = 1;
unit_name = "ns";
} else if (avg_time <= time.millisecond) {
unit = time.microsecond;
unit_name = "us";
} else {
unit = time.millisecond;
unit_name = "ms";
}
warn("{} <{}>: avg {d:.3}{} ({} iterations)\n", .{ name, if (@TypeOf(a) == type) @typeName(a) else a, ctx.averageTime(unit), unit_name, ctx.iter });
}
}
pub fn doNotOptimize(value: var) void {
// LLVM triggers an assert if we pass non-trivial types as inputs for the
// asm volatile expression.
// Workaround until asm support is better on Zig's end.
const T = @TypeOf(value);
const typeId = @typeId(T);
switch (typeId) {
.Bool, .Int, .Float => {
asm volatile (""
:
: [_] "r,m" (value)
: "memory"
);
},
.Optional => {
if (value) |v| doNotOptimize(v);
},
.Struct => {
inline for (comptime std.meta.fields(T)) |field| {
doNotOptimize(@field(value, field.name));
}
},
.Type, .Void, .NoReturn, .ComptimeFloat, .ComptimeInt, .Undefined, .Null, .Fn, .BoundFn => @compileError("doNotOptimize makes no sense for " ++ @tagName(typeId)),
else => @compileError("doNotOptimize is not implemented for " ++ @tagName(typeId)),
}
}
pub fn clobberMemory() void {
asm volatile (""
:
:
: "memory"
);
}
test "benchmark" {
const benchSleep57 = struct {
fn benchSleep57(ctx: *Context) void {
while (ctx.run()) {
time.sleep(57 * time.millisecond);
}
}
}.benchSleep57;
std.debug.warn("\n", .{});
benchmark("Sleep57", benchSleep57);
}
test "benchmarkArgs" {
const benchSleep = struct {
fn benchSleep(ctx: *Context, ms: u32) void {
while (ctx.run()) {
time.sleep(ms * time.millisecond);
}
}
}.benchSleep;
std.debug.warn("\n", .{});
benchmarkArgs("Sleep", benchSleep, &[_]u32{ 20, 30, 57 });
}
test "benchmarkArgs types" {
const benchMin = struct {
fn benchMin(ctx: *Context, comptime intType: type) void {
while (ctx.run()) {
time.sleep(std.math.min(37, 48) * time.millisecond);
}
}
}.benchMin;
std.debug.warn("\n", .{});
benchmarkArgs("Min", benchMin, &[_]type{ u32, u64 });
}
test "benchmark custom timing" {
const sleep = struct {
fn sleep(ctx: *Context) void {
while (ctx.runExplicitTiming()) {
time.sleep(30 * time.millisecond);
ctx.startTimer();
defer ctx.stopTimer();
time.sleep(10 * time.millisecond);
}
}
}.sleep;
std.debug.warn("\n", .{});
benchmark("sleep", sleep);
}