diff --git a/lib/p2/src/structures/pscopes.zig b/lib/p2/src/structures/pscopes.zig index a1ea80f..81087ab 100644 --- a/lib/p2/src/structures/pscopes.zig +++ b/lib/p2/src/structures/pscopes.zig @@ -4,7 +4,7 @@ // // 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 { 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 { // value in tsc ticks startTsc: u64, @@ -59,7 +65,14 @@ pub const TimingScope = struct { } 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 { @@ -73,7 +86,11 @@ pub const ScopesContext = struct { timer: std.time.Timer, pub fn timingScope(self: *@This()) TimingScope { - _ = self; + return .{ + .startTsc = timestampTicks(), + .endTsc = null, + .context = self, + }; } // calibrates the ticks per second divider. @@ -125,6 +142,14 @@ test "calibrate scoes" { std.debug.print("calibration ticksPerMs = {d}\n", .{scopes.ticksPerMs.?}); scopes.calibrate(); 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");