Created
April 16, 2025 08:16
-
-
Save VendettaReborn/394793e40a8860140e31fe40a26951b7 to your computer and use it in GitHub Desktop.
experiment in rust for cacheline false sharing
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::Arc; | |
use std::thread; | |
use std::time::Instant; | |
fn main() { | |
// Number of iterations for our test | |
const ITERATIONS: u64 = 100_000_000; | |
println!("Running cache false sharing experiment..."); | |
println!("Iterations per thread: {}", ITERATIONS); | |
// Using atomics instead of locks (more realistic for performance testing) | |
println!("\nRunning experiment with atomics (more realistic):"); | |
// Test with false sharing using atomics | |
{ | |
use std::sync::atomic::{AtomicU64, Ordering}; | |
struct AtomicShared { | |
a: AtomicU64, | |
b: AtomicU64, | |
} | |
#[repr(align(64))] | |
struct AtomicPadded { | |
a: AtomicU64, | |
_pad1: [u64; 7], | |
b: AtomicU64, | |
_pad2: [u64; 7], | |
} | |
// With false sharing | |
let shared = Arc::new(AtomicShared { | |
a: AtomicU64::new(0), | |
b: AtomicU64::new(0), | |
}); | |
let shared_clone = Arc::clone(&shared); | |
let start = Instant::now(); | |
let t1 = thread::spawn(move || { | |
for _ in 0..ITERATIONS { | |
shared.a.fetch_add(1, Ordering::SeqCst); | |
} | |
}); | |
let t2 = thread::spawn(move || { | |
for _ in 0..ITERATIONS { | |
shared_clone.b.fetch_add(1, Ordering::SeqCst); | |
} | |
}); | |
t1.join().unwrap(); | |
t2.join().unwrap(); | |
let duration = start.elapsed(); | |
println!("Time with atomics and false sharing: {:?}", duration); | |
// Without false sharing (padded) | |
let padded = Arc::new(AtomicPadded { | |
a: AtomicU64::new(0), | |
_pad1: [0; 7], | |
b: AtomicU64::new(0), | |
_pad2: [0; 7], | |
}); | |
let padded_clone = Arc::clone(&padded); | |
let start = Instant::now(); | |
let t1 = thread::spawn(move || { | |
for _ in 0..ITERATIONS { | |
padded.a.fetch_add(1, Ordering::SeqCst); | |
} | |
}); | |
let t2 = thread::spawn(move || { | |
for _ in 0..ITERATIONS { | |
padded_clone.b.fetch_add(1, Ordering::SeqCst); | |
} | |
}); | |
t1.join().unwrap(); | |
t2.join().unwrap(); | |
let duration = start.elapsed(); | |
println!("Time with atomics and padding: {:?}", duration); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment