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 std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::thread;
Aggregating metrics across threads in Rust
concurrency
shared-state
mutex
Intermediate
7 steps
rust
use std::sync::{mpsc, Arc, Mutex}; use std::thread; use std::time::Duration;
Building a thread pool in Rust
concurrency
channels
thread-pool
Advanced
9 steps
rust
use std::collections::HashMap; pub struct Memoizer<K, V, F> { cache: HashMap<K, V>,
A generic memoizer in Rust
memoization
generics
caching
Intermediate
6 steps
rust
use std::collections::HashMap; #[derive(Debug, Clone)] struct Order {
Aggregating Rust data with fold and entry
fold
hashmap
ownership
Intermediate
6 steps
rust
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json}; use serde::{Deserialize, Serialize}; use uuid::Uuid;
Building a typed create_user handler in Axum
serde
extractors
sqlx
Intermediate
7 steps
rust
use axum::{ response::sse::{Event, KeepAlive, Sse}, routing::get, Router,
Streaming live price ticks with SSE in Axum
server-sent-events
broadcast-channel
streaming
Advanced
8 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.