Last active
February 14, 2020 16:44
-
-
Save ronlobo/934facdc7b04521cefa0dd5bbe704968 to your computer and use it in GitHub Desktop.
Codingame thread performance test, tl;dr unthreaded runs ~2.5x faster
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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