This is a really interesting idea, will give it a try! BTW, will the precision of things like
setitimer(2) and
usleep(3) depend on this setting?
I was wrong, I just checked: HZ is set to 300 only (I did that via kernel configuration, not via
loader.conf(5)). This is both on my desktop and on my home server. My mp3 player has HZ=100.
setitimer(2) and
getitimer(2) use “ticks” accuracy (i.e. 1/HZ). Portable applications should not assume any specific resolution; it’s probably best to assume a resolution of 10 ms. If you need more than that, use
clock_gettime(2) (see below).
In contrast,
usleep(3) is just a wrapper around
nanosleep(2), which in turn calls
clock_nanosleep(CLOCK_REALTIME)
, which uses full timer resolution. This is also what
clock_gettime(2) uses.
The actual resolution is hardware-dependent (and portable programs should not rely on it). To find out what you have, look at the
kern.timecounter.hardware
sysctl. It tells you which one of the various hardware clocks were selected for the kernel’s time counter base. Then you can look up its frequency with the
kern.timecounter.tc.
<name>.frequency
sysctl.
For example, the system that I’m sitting in front of right now has this:
Code:
olli@ryzen:~ > COUNTER=$(sysctl -n kern.timecounter.hardware)
olli@ryzen:~ > echo $COUNTER
TSC-low
olli@ryzen:~ > FREQ=$(sysctl -n sysctl kern.timecounter.tc.$COUNTER.frequency)
olli@ryzen:~ > echo $FREQ
1597043936
olli@ryzen:~ > awk "BEGIN {print 1000^3 / $FREQ}"
0.626157
So, the resolution would be roughly 0.626 ns in this case (0.000626 µs).
Of course, that’s only the theoretical maximum resolution. FreeBSD is not a real-time OS (and it can’t be, because typical PC hardware is not real-time capable). For example, at any time, the scheduler may decide to put another process on the CPU and suspend your own process, so the time value that you just fetched may be moot. Not even
rtprio(1) gives you any kind of guarantee. Also keep in mind that calls to
usleep(3) and
nanosleep(2) may return prematurely when a signal is delivered to the process.