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 axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
rust
use std::net::Ipv4Addr; use std::str::FromStr; #[derive(Debug, Clone, Copy)]
Parsing and matching IPv4 CIDR ranges in Rust
bitwise-operations
parsing
error-handling
Intermediate
8 steps
rust
use std::sync::OnceLock; static CRC_TABLE: OnceLock<[u32; 256]> = OnceLock::new();
Table-driven CRC32 with lazy init in Rust
checksums
lazy-initialization
lookup-tables
Intermediate
8 steps
rust
use axum::{ body::Body, extract::Path, http::{header, HeaderMap, HeaderValue, StatusCode},
HTTP range requests for video streaming in Axum
http-range-requests
streaming
async-io
Advanced
8 steps
rust
use std::sync::mpsc; use std::thread; use std::time::Duration;
Running work with a timeout in Rust
concurrency
channels
timeout
Intermediate
7 steps
rust
use axum::{extract::State, response::IntoResponse, Json}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::sync::Arc;
Building a JSON-RPC 2.0 handler in Axum
json-rpc
serde
request-dispatch
Intermediate
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.