Expand description
kala provides a simple API for timing sections of code with sub-nanosecond
precision. It can run and time a function while preventing interference from CPU
and compiler instruction reordering. It uses CPU hardware clock counters
like the Time Stamp Counter (TSC) on x86-64 or the Cycle Counter
Register (CCNT) on AArch64 (with an std::time::Instant fallback on
other architectures).
§Example
use kala::Stopwatch;
let sw = Stopwatch::new(); // Most efficient to create once and re-use.
let nanos: f64 = sw.time(|| 2 + 3).to_nanos(); // Runs closure _once_.
println!("Function took {nanos:.2} nanos");§Note on Precision
While kala goes to extreme lengths to provide the highest level of timing
precision, ultimately measurement precision depends on your CPU. Some
CPUs—especially those using the AArch64 architecture—have very coarse
CPU time counters. For instance, the Apple M1 and M2 (but not M3 and later)
use a CPU time counter with a 24 MHz frequency. Thus the clock “ticks” every
~41.67 nanoseconds. No other clock source on that CPU can offer better
granularity.
It’s still possible to extract finer timing precision from such data, but
that requires collecting many measurements with an excellent experiment
design and great statistics. This is the job of benchmarking harnesses that
use kala, not kala itself.
See the API docs for kala::Duration for advice on avoiding
conversion losses and getting the highest precision.