Cache the result of a function

cache time

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"

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo