Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 21, 2020 16:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/e6036d23879b0d0abda5196dfa8a131e to your computer and use it in GitHub Desktop.
Save rust-play/e6036d23879b0d0abda5196dfa8a131e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::collections::HashMap;
use std::thread;
use std::time::Instant;
const NUM_ELEMENTS: usize = 1000000;
type HeavyThings = HashMap<usize, Vec<usize>>;
fn main() {
let heavy_things_1 = make_heavy_things();
let heavy_things_2 = make_heavy_things();
let len =log_time("drop in another thread", || {
fn_that_drops_heavy_things_in_another_thread(heavy_things_2)
});
assert_eq!(len, NUM_ELEMENTS);
let len = log_time("drop in this thread", || {
fn_that_drops_heavy_things(heavy_things_1)
});
assert_eq!(len, NUM_ELEMENTS);
}
fn make_heavy_things() -> HeavyThings {
(1..=NUM_ELEMENTS).map(|v| (v, vec![v])).collect()
}
fn fn_that_drops_heavy_things(things: HeavyThings) -> usize {
things.len()
}
fn fn_that_drops_heavy_things_in_another_thread(things: HeavyThings) -> usize {
let len = things.len();
thread::spawn(move || drop(things));
len
}
fn log_time<T, F: FnOnce() -> T>(name: &str, f: F) -> T {
let time = Instant::now();
let result = f();
println!("{} {:?}", name, time.elapsed());
result
}
// drop in another thread 87.471µs
// drop in this thread 907.369466ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment