Created
August 17, 2024 13:22
-
-
Save bhb/7dc0df53a1a7b18ba04c786d76859c44 to your computer and use it in GitHub Desktop.
Timers in Zig (MacOS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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