Course contentsShow
← Rust
Lesson 1457 of 1,91012. Unsafe Rust and Low-Level AccessFree lesson

Deterministic Execution Timers

You will use high-resolution hardware timers to measure the execution latency of sensitive code sections.

In this lesson, you will learn how to bypass standard system clocks to measure code execution latency with cycle-level precision using hardware-specific deterministic timers.

The Problem with System Clocks

When dealing with low-level systems or highly sensitive code, using standard library functions like std::time::Instant is often inadequate. These rely on the OS kernel, which introduces non-deterministic jitter due to context switching, interrupt handling, and system call overhead. To measure a "hot" block of code deterministically, we must interact directly with the CPU’s time-stamp counter.

Measuring with the Time-Stamp Counter

On x86 architectures, the RDTSC (Read Time-Stamp Counter) instruction returns the number of clock cycles since the CPU was reset. By wrapping this in an unsafe block, we can capture the CPU state immediately before and after a specific operation.

To ensure deterministic results, we must prevent the compiler from reordering instructions across our timer—a concept we touched upon in our previous lessons on instruction scheduling. We use the cpuid instruction or an "asm block" clobber to create a serialization barrier.

use core::arch::x86_64::{_rdtsc, __cpuid};

fn measure_latency<F: Fn()>(f: F) -> u64 {
    unsafe {
        // Serialize the pipeline to ensure the timer doesn't drift
        __cpuid(0);
        let start = _rdtsc();
        
        f();
        
        let end = _rdtsc();
        __cpuid(0);
        
        end - start
    }
}

Ensuring Determinism

Simply reading the register isn't enough. Modern Out-of-Order Execution (OoOE) CPUs might move instructions from your measured code block outside the time window, or vice-versa. The __cpuid call acts as a "serializing instruction," forcing the CPU to finish all previous instructions before proceeding. This guarantees that your measurement strictly captures the latency of the provided closure, free from the influence of surrounding code.

Note that while this is highly precise, it is strictly hardware-dependent. If the CPU frequency scales (e.g., via Turbo Boost), the cycle count may not map linearly to wall-clock time, but it remains the gold standard for measuring instruction-level execution paths.

Key Takeaway: Deterministic execution timers leverage serializing hardware instructions to bypass OS jitter and measure raw CPU cycle latency with absolute precision.