Hardware-based tick counters for high-precision benchmarks

crates.io docs build & test license

x86_64: executes RDTSC CPU instruction to read the time-stamp counter.

AArch64: reads value of the CNTVCT_EL0 counter-timer register.

Tested on platforms

text x86_64 (Intel® Core™ i7) AArch64 (Apple M1 Pro)

Usage

For usage samples please look at src/bin/sample.rs

Basic usage

rust let start = tick_counter::start(); // ... lines of code to benchmark let elapsed_ticks = tick_counter::stop() - start; println!("Number of elapsed ticks: {}", elapsed_ticks);

Basic usage with helper

```rust use tick_counter::TickCounter;

let tickcounter = TickCounter::current(); // ... lines of code to benchmark let elapsedticks = tickcounter.elapsed(); println!("Number of elapsed ticks: {}", elapsedticks); ```

Extended usage

```rust use std::{thread, time, env::consts};

println!("Environment: {}/{} {}", consts::OS, consts::FAMILY, consts::ARCH);

let (counterfrequency, accuracy) = tickcounter::frequency(); println!("Tick frequency, MHZ: {}", counterfrequency as f64 / 1e6f64); let estimationsource = match accuracy { tickcounter::TickCounterFrequencyBase::Hardware => "hardware".tostring(), tickcounter::TickCounterFrequencyBase::Measured(duration) => format!("software, estimated in {:?}", duration) }; println!("Tick frequency is provided by: {}", estimation_source);

let counteraccuracy = tickcounter::precision(counterfrequency); println!("Tick accuracy, nanoseconds: {}", counteraccuracy);

let counterstart = tickcounter::start(); thread::sleep(time::Duration::fromsecs(1)); let counterstop = tick_counter::stop();

println!("Tick counter start: {}", counterstart); println!("Tick counter stop: {}", counterstop);

let elapsedticks = counterstop - counterstart; println!("Elapsed ticks count in ~1 seconds thread::sleep(): {}", elapsedticks);

let elapsednanoseconds = (elapsedticks as f64) * counteraccuracy; println!("Elapsed nanoseconds according to elapsed ticks: {}", elapsednanoseconds); ```

Outputs

1. Macbook Pro 16 2021 / Apple Silicon

```text Apple M1 Pro MacOS Ventura 13.4, Darwin Kernel Version 22.5.0

Output:

Environment: macos/unix aarch64 Tick frequency, MHZ: 24 Tick frequency is provided by: hardware Tick accuracy, nanoseconds: 41.666666666666664 Tick counter start: 48031196281005 Tick counter stop: 48031220402058 Elapsed ticks count in ~1 seconds thread::sleep(): 24121053 Elapsed nanoseconds according to elapsed ticks: 1005043875 ```

2. Ubuntu 22.04 LTS / Intel® Core™ i7

```text Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz Linux 5.19.0-46-generic #47~22.04.1-Ubuntu

Output:

Environment: linux/unix x86_64 Tick frequency, MHZ: 3430.481526 Tick frequency is provided by: software, estimated in 1s Tick accuracy, nanoseconds: 0.29150426621478326 Tick counter start: 9639567570396 Tick counter stop: 9642998073707 Elapsed ticks count in ~1 seconds thread::sleep(): 3430503311 Elapsed nanoseconds according to elapsed ticks: 1000006350.4204394 ```