rust 43 lines · 7 steps

A scope-guard timer with Drop in Rust

A struct that captures a start time on creation and logs the elapsed duration automatically when it goes out of scope.

Explained by highlit
1use std::time::Instant;
2use tracing::info;
3 
4pub struct Timer {
5 label: &'static str,
6 start: Instant,
7}
8 
9impl Timer {
10 pub fn start(label: &'static str) -> Self {
11 Self {
12 label,
13 start: Instant::now(),
14 }
15 }
16}
17 
18impl Drop for Timer {
19 fn drop(&mut self) {
20 let elapsed = self.start.elapsed();
21 info!(
22 label = self.label,
23 elapsed_ms = elapsed.as_secs_f64() * 1000.0,
24 "completed in {:.2?}",
25 elapsed
26 );
27 }
28}
29 
30pub fn rebuild_search_index(documents: &[Document]) -> Result<IndexStats, IndexError> {
31 let _timer = Timer::start("rebuild_search_index");
32 
33 let mut writer = SearchWriter::open()?;
34 for doc in documents {
35 writer.add(doc.id, &doc.tokenized_body())?;
36 }
37 writer.commit()?;
38 
39 Ok(IndexStats {
40 documents: documents.len(),
41 segments: writer.segment_count(),
42 })
43}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing `Drop` turns a value's end-of-scope into a guaranteed cleanup or measurement hook.
  2. 2Binding a guard to a local like `_timer` ties its lifetime to the enclosing block without any manual teardown.
  3. 3RAII makes instrumentation robust because the timer fires even when an early `?` return aborts the function.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A scope-guard timer with Drop in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code