#linux #perf


A Rust interface to Linux performance monitoring

13 releases

0.4.8 Nov 7, 2022
0.4.7 Apr 27, 2021
0.4.6 Dec 12, 2020
0.4.5 Aug 18, 2020
0.4.2 Dec 22, 2019

#18 in Profiling

Download history 13195/week @ 2023-02-11 10795/week @ 2023-02-18 15182/week @ 2023-02-25 11898/week @ 2023-03-04 14120/week @ 2023-03-11 10732/week @ 2023-03-18 13861/week @ 2023-03-25 12307/week @ 2023-04-01 14069/week @ 2023-04-08 11295/week @ 2023-04-15 14356/week @ 2023-04-22 10812/week @ 2023-04-29 11305/week @ 2023-05-06 12534/week @ 2023-05-13 13312/week @ 2023-05-20 10480/week @ 2023-05-27

49,693 downloads per month
Used in 56 crates (5 directly)


584 lines

perf-event: a Rust interface to Linux performance monitoring

This uses the Linux perf_event_open API to access performance monitoring hardware and software. Use Builder to create a perf event counter, then use enable and disable to start and stop counting. Call read to get your count.

For example, this counts the number of cycles used by the call to println!. Try adjusting the length of the vector to see the cycle count change.

use perf_event::Builder;

fn main() -> std::io::Result<()> {
    let mut counter = Builder::new().build()?;

    let vec = (0..=51).collect::<Vec<_>>();

    println!("{:?}", vec);

    println!("{} instructions retired", counter.read()?);


Since we don't specify what sort of event we want to count, Builder defaults to PERF_COUNT_HW_INSTRUCTIONS events, whose documentation says:

Retired instructions. Be careful, these can be affected by various issues, most notably hardware interrupt counts.

The examples directory includes programs that count other sorts of events.

See also

The perfcnt crate provides more extensive coverage of the Linux perf_event_open API than this crate.

Markus Stange's linux-perf-event-reader supports events. This crate only handles counters for now.

The not-perf project is a rewrite of perf in Rust, and has a bunch of code for dealing with the Linux perf API.