Skip to content

Commit 974fb54

Browse files
committed
Add memcpy example benchmarks
1 parent c04e6bd commit 974fb54

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

examples/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,10 @@ required-features = ["image"]
7373
name = "math"
7474
harness = false
7575

76+
[[bench]]
77+
name = "memcpy"
78+
harness = false
79+
7680
[[bench]]
7781
name = "panic"
7882
harness = false

examples/benches/memcpy.rs

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
use divan::{counter::BytesCount, Bencher};
2+
use fastrand::Rng;
3+
4+
fn main() {
5+
divan::main();
6+
}
7+
8+
const LENS: &[usize] = &[
9+
1,
10+
2,
11+
8,
12+
16,
13+
64,
14+
512,
15+
1024 * 4,
16+
1024 * 16,
17+
1024 * 64,
18+
1024 * 256,
19+
1024 * 1024,
20+
1024 * 1024 * 4,
21+
];
22+
23+
fn gen_inputs(len: usize) -> impl FnMut() -> [Box<[u8]>; 2] {
24+
let mut rng = Rng::default();
25+
move || {
26+
// Very buffers by length rather than adhere to nice numbers.
27+
let max_len = len + (len / 8);
28+
let lens = [rng.usize(len..=max_len), rng.usize(len..=max_len)];
29+
30+
lens.map(|len| (0..len).map(|_| rng.u8(..)).collect())
31+
}
32+
}
33+
34+
#[divan::bench(consts = LENS)]
35+
fn memcpy<const N: usize>(bencher: Bencher) {
36+
bencher.counter(BytesCount::new(N)).with_inputs(gen_inputs(N)).bench_local_refs(
37+
|[src, dst]| unsafe {
38+
let src = src.as_ptr().cast();
39+
let dst = dst.as_mut_ptr().cast();
40+
libc::memcpy(dst, src, N);
41+
},
42+
)
43+
}
44+
45+
#[divan::bench(consts = LENS)]
46+
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
47+
fn movsb<const N: usize>(bencher: Bencher) {
48+
use std::arch::asm;
49+
50+
bencher.counter(BytesCount::new(N)).with_inputs(gen_inputs(N)).bench_local_refs(
51+
|[src, dst]| unsafe {
52+
let src = src.as_ptr();
53+
let dst = dst.as_mut_ptr();
54+
55+
#[cfg(target_arch = "x86")]
56+
asm!(
57+
"rep movsb",
58+
inout("ecx") N => _,
59+
inout("esi") src => _,
60+
inout("edi") dst => _,
61+
options(nostack, preserves_flags),
62+
);
63+
64+
#[cfg(target_arch = "x86_64")]
65+
asm!(
66+
"rep movsb",
67+
inout("rcx") N => _,
68+
inout("rsi") src => _,
69+
inout("rdi") dst => _,
70+
options(nostack, preserves_flags),
71+
);
72+
},
73+
)
74+
}

0 commit comments

Comments
 (0)