liveBook · Manning

Profiling

As explained in Embedded Software with Rust

Profiling is the measurement of a program's execution behavior to characterize its performance.

Profiling measures execution behavior to characterize performance. In embedded Rust, cycle counters can time a region of code without relying on print-based measurement, which can distort timing. section 6.0 section 6.7

Choose a timing source that fits the target and existing firmware:

  • Use the DWT cycle counter on Cortex-M3 and later; its 32-bit width reduces the need to handle counter wraps. section 6.7
  • Use SysTick as a fallback where DWT is unavailable. Its 24-bit down-counter can handle a single wrap, but not multiple wraps without a separate wrap counter. section 6.6.4
  • Avoid repurposing SysTick when an RTOS or delay routine already depends on it; a general-purpose timer may be a better choice. section 6.6.4
#![no_main]
#![no_std]

use cortex_m::peripheral::{syst::SystClkSource, SYST};
use cortex_m_rt::entry;
use panic_halt as _;
use rtt_target::{rtt_init_print, rprintln};

const SYSTICK_RELOAD: u32 = 0x00FF_FFFF; // 24-bit maximum

fn do_work() {
    for _ in 0..10_000 {
        cortex_m::asm::nop();
    }
}

#[entry]
fn main() -> ! {
    rtt_init_print!();
    rprintln!("Starting SysTick profiling...");

    let cp = cortex_m::Peripherals::take().unwrap();
    let mut syst = cp.SYST;

    syst.set_clock_source(SystClkSource::Core);
    syst.set_reload(SYSTICK_RELOAD);
    syst.clear_current();
    syst.enable_counter();

    let start = SYST::get_current();
    do_work();
    let end = SYST::get_current();

    // SysTick counts down. wrapping_sub() handles a single wrap correctly;
    // masking to 24 bits trims any high bits that could appear from the
    // 32-bit subtraction. The caller must ensure the measured region is
    // shorter than one full reload period — multi-wrap intervals are not
    // detected by this code.
    let elapsed = start.wrapping_sub(end) & SYSTICK_RELOAD;

    rprintln!("do_work() took {} cycles", elapsed);

    loop {}
}

The example configures SysTick to count core-clock cycles, times a loop of no-op instructions, then computes elapsed cycles while accounting for a single wrap. section 6.6.4

How Embedded Software with Rust covers it

How deep it goes
Explains DWT and SysTick timing, including counter width, wrap limits, and conflicts with existing SysTick use.
Examples
Times a loop of 10,000 no-op instructions using SysTick on a core without DWT.
What you can do after
Apply a SysTick timing pattern to measure a code region, accounting for a single counter wrap.
How it connects
Connects profiling to DWT, SysTick, and embedded debugging.

Also explained in

Compare how 15 books explain profiling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.