Created
March 2, 2022 11:14
-
-
Save Jimmy-Z/cf53b851e9e86e363b5343c0b93b8e5f to your computer and use it in GitHub Desktop.
rust vec new/fill test
This file contains 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 libc::memset; | |
use std::mem::size_of; | |
use std::time::Instant; | |
use rand::rngs::SmallRng; | |
use rand::{Rng, SeedableRng}; | |
// test a, each call creates its own vec | |
fn testa(l: usize, m: usize){ | |
for _ in 0..m { | |
suba(l); | |
} | |
} | |
// and sub a only write a single element | |
fn suba(l: usize){ | |
let mut v: Vec<isize> = vec![0; l]; | |
v[l >> 2] = 2501; | |
} | |
// test 0, each call creates its own vec | |
fn test0(l: usize, m: usize){ | |
for _ in 0..m { | |
sub0(l); | |
} | |
} | |
const STRIDE: usize = 8; | |
fn sub0(l: usize){ | |
let mut v: Vec<isize> = vec![0; l]; | |
for i in 0..(v.len() >> STRIDE) { | |
v[i << STRIDE] = 2501; | |
} | |
} | |
// test 1, use a persistent vec, zero it using fill | |
fn test1(l: usize, m: usize){ | |
let mut v = vec![0; l]; | |
for _ in 0..m { | |
v.fill(0); | |
sub1(&mut v); | |
} | |
} | |
fn sub1(v: &mut Vec<isize>){ | |
for i in 0..(v.len() >> STRIDE) { | |
v[i << STRIDE] = 2501; | |
} | |
} | |
// test 2, use a persistent vec, zero it using unsafe libc::memset | |
fn test2(l: usize, m: usize){ | |
let mut v = vec![0; l]; | |
for _ in 0..m { | |
unsafe { | |
memset( | |
v.as_mut_ptr() as _, | |
0, | |
v.len() * size_of::<isize>(), | |
); | |
} | |
sub1(&mut v); | |
} | |
} | |
// test 3, use a persistent vec, zero only used elements | |
fn test3(l: usize, m: usize) { | |
let mut v = vec![0; l]; | |
let mut used = vec![0; 0]; | |
let mut rng = SmallRng::seed_from_u64(2501); | |
for _ in 0..(1 << 10) { | |
used.push(rng.gen_range(0..l)); | |
} | |
for _ in 0..m { | |
for i in &used { | |
v[*i] = 0; | |
} | |
sub1(&mut v); | |
} | |
} | |
fn test(name: &str, p0: usize, p1: usize, test_fn: fn(usize, usize)){ | |
let t0 = Instant::now(); | |
test_fn(p0, p1); | |
let t1 = Instant::now(); | |
println!("test {} {} * {}: {:.6}s", name, p0, p1, (t1 - t0).as_secs_f64()); | |
} | |
fn main() { | |
for l in 16..18 { | |
for m in 16..18{ | |
test("a", 1 << l, 1 << m, testa); | |
test("0", 1 << l, 1 << m, test0); | |
test("1", 1 << l, 1 << m, test1); | |
test("2", 1 << l, 1 << m, test2); | |
test("3", 1 << l, 1 << m, test3); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment