This commit is contained in:
peterino2 2025-10-31 00:55:27 -07:00
parent c7cfa18ce9
commit 08bad270e6
1 changed files with 28 additions and 3 deletions

View File

@ -4,7 +4,7 @@
// //
// as well as contains info for arbitrary timestamping and timestamp resolution // as well as contains info for arbitrary timestamping and timestamp resolution
const timestampTicks = if (builtin.target.cpu.arch == .x86_64) aarch64_ticks else rdtsc; const timestampTicks = if (builtin.target.cpu.arch == .x86_64) rdtsc else aarch64_ticks;
pub inline fn rdtsc_fenced() u64 { pub inline fn rdtsc_fenced() u64 {
var hi: u32 = 0; var hi: u32 = 0;
@ -44,6 +44,12 @@ fn aarch64_freq() u64 {
); );
} }
fn countTo1Billion() u32 {
var i: u32 = 0;
while (i < 1000 * 1000 * 1000) : (i += 1) {}
return i;
}
pub const TimingScope = struct { pub const TimingScope = struct {
// value in tsc ticks // value in tsc ticks
startTsc: u64, startTsc: u64,
@ -59,7 +65,14 @@ pub const TimingScope = struct {
} }
pub fn duration(self: *@This()) ?f64 { pub fn duration(self: *@This()) ?f64 {
_ = self; if (self.endTsc) |endTsc| {
if (self.context.ticksPerMs) |ticksPerMs| {
const x = @as(f64, @floatFromInt(endTsc - self.startTsc)) / ticksPerMs / 1000;
return x;
}
}
return null;
} }
pub inline fn end(self: *@This()) void { pub inline fn end(self: *@This()) void {
@ -73,7 +86,11 @@ pub const ScopesContext = struct {
timer: std.time.Timer, timer: std.time.Timer,
pub fn timingScope(self: *@This()) TimingScope { pub fn timingScope(self: *@This()) TimingScope {
_ = self; return .{
.startTsc = timestampTicks(),
.endTsc = null,
.context = self,
};
} }
// calibrates the ticks per second divider. // calibrates the ticks per second divider.
@ -125,6 +142,14 @@ test "calibrate scoes" {
std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?}); std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?});
scopes.calibrate(); scopes.calibrate();
std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?}); std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?});
{
var scope = scopes.timingScope();
_ = countTo1Billion();
scope.end();
std.debug.print("time elapsed: {d}\n ", .{scope.duration().?});
}
} }
const std = @import("std"); const std = @import("std");