Skip to content

Instantly share code, notes, and snippets.

@bhb
Created August 17, 2024 13:22
Show Gist options
  • Save bhb/7dc0df53a1a7b18ba04c786d76859c44 to your computer and use it in GitHub Desktop.
Save bhb/7dc0df53a1a7b18ba04c786d76859c44 to your computer and use it in GitHub Desktop.
Timers in Zig (MacOS)
const builtin = @import("builtin");
const std = @import("std");
const time = @cImport({
@cInclude("sys/time.h");
});
pub const OsTimerFreq = 1_000_000;
pub fn readOsTimer() u64 {
var value = time.timeval{
.tv_sec = 0, // Seconds
.tv_usec = 0, // Microseconds
};
_ = time.gettimeofday(&value, null);
return OsTimerFreq * @as(u64, @bitCast(value.tv_sec)) + @as(u32, @bitCast(value.tv_usec));
}
// Might need another instruction to figure out timer frequency?
// https://cpufun.substack.com/i/32886352/aarch-timer
pub fn readCpuFreq() u64 {
var val: u64 = undefined;
asm volatile ("mrs %[val], cntvfreq_el0"
: [val] "=r" (val),
);
return val;
}
pub fn readCpuTimer() u64 {
var val: u64 = undefined;
asm volatile ("mrs %[val], cntvct_el0"
: [val] "=r" (val),
);
return val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment