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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing `Drop` turns a value's end-of-scope into a guaranteed cleanup or measurement hook.
- 2Binding a guard to a local like `_timer` ties its lifetime to the enclosing block without any manual teardown.
- 3RAII makes instrumentation robust because the timer fires even when an early `?` return aborts the function.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-scope-guard-timer-with-drop-in-rust-explained-rust-6055/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.