Skip to content

Instantly share code, notes, and snippets.

@ronlobo
Last active February 14, 2020 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronlobo/934facdc7b04521cefa0dd5bbe704968 to your computer and use it in GitHub Desktop.
Save ronlobo/934facdc7b04521cefa0dd5bbe704968 to your computer and use it in GitHub Desktop.
Codingame thread performance test, tl;dr unthreaded runs ~2.5x faster
use std::sync::{Mutex, Arc};
use std::thread;
use std::time::Instant;
fn main() {
let threaded_counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
let timer = Instant::now();
for _ in 0..2 {
let counter = Arc::clone(&threaded_counter);
let handle = thread::spawn(move || {
let result = compute();
let mut num = counter.lock().unwrap();
*num += result;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
let duration = timer.elapsed();
eprintln!(" Threaded version, Result: {}, Duration: {} ns", *threaded_counter.lock().unwrap(), duration.as_nanos());
let timer = Instant::now();
let mut unthreaded_counter = 0;
for _ in 0..2 {
let result = compute();
unthreaded_counter += result;
}
let duration = timer.elapsed();
eprintln!("Unthreaded version, Result: {}, Duration: {} ns", unthreaded_counter, duration.as_nanos());
}
fn compute() -> i32 {
let mut result: i32 = 0;
for i in 0..1000 {
result += i;
}
result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment