I have some code where I wanted to cache the result of a function. I found the cached crate to be useful.
Here is the first experiment with it showing how it caches the value in one function, but not in the other. The first 2 tv_nsec values differ, as time have elapsed between the calls. The 3rd and 4th tv_nsec values are the same as the value got cached after the first call.
examples/cache-result-of-function/src/main.rs
use std::time::SystemTime;
use cached::macros::cached;
fn main() {
let time = get_current_time();
println!("Current time: {:?}", time);
let time = get_current_time();
println!("Current time: {:?}", time);
let time = get_cached_time();
println!("Cacehed time: {:?}", time);
let time = get_cached_time();
println!("Cacehed time: {:?}", time);
}
fn get_current_time() -> SystemTime {
SystemTime::now()
}
#[cached]
fn get_cached_time() -> SystemTime {
SystemTime::now()
}
examples/cache-result-of-function/out.txt
Current time: SystemTime { tv_sec: 1781167332, tv_nsec: 68780987 }
Current time: SystemTime { tv_sec: 1781167332, tv_nsec: 68846651 }
Cacehed time: SystemTime { tv_sec: 1781167332, tv_nsec: 68882989 }
Cacehed time: SystemTime { tv_sec: 1781167332, tv_nsec: 68882989 }
examples/cache-result-of-function/Cargo.toml
[package]
name = "cache-result-of-function"
version = "0.1.0"
edition = "2024"
[dependencies]
cached = "2.0.2"