README.md
1## perf-event: a Rust interface to Linux performance monitoring
2
3*This is a nascent project. Tests are lacking. The design may change.*
4
5This uses the Linux [`perf_event_open`][man] API to access performance monitoring
6hardware and software. Use `Builder` to create a perf event counter, then use
7`enable` and `disable` to start and stop counting. Call `read` to get your
8count.
9
10For example, this counts the number of cycles used by the call to `println!`.
11Try adjusting the length of the vector to see the cycle count change.
12
13 use perf_event::Builder;
14
15 fn main() -> std::io::Result<()> {
16 let mut counter = Builder::new().build()?;
17
18 let vec = (0..=51).collect::<Vec<_>>();
19
20 counter.enable()?;
21 println!("{:?}", vec);
22 counter.disable()?;
23
24 println!("{} instructions retired", counter.read()?);
25
26 Ok(())
27 }
28
29Since we don't specify what sort of event we want to count, `Builder` defaults
30to `PERF_COUNT_HW_INSTRUCTIONS` events, whose documentation says:
31
32> Retired instructions. Be careful, these can be affected by various issues,
33> most notably hardware interrupt counts.
34
35The `examples` directory includes programs that count other sorts of events.
36
37[man]: http://man7.org/linux/man-pages/man2/perf_event_open.2.html
38
39## See also
40
41The [`perfcnt`] crate provides more extensive coverage of the Linux
42`perf_event_open` API than this crate. However, `perfcnt` does not build on
43stable Rust.
44
45[`perfcnt`]: https://crates.io/crates/perfcnt
46