Created
June 12, 2021 09:44
-
-
Save maxleiko/f4f02d790276d551815d38017889ab51 to your computer and use it in GitHub Desktop.
Benchmark different buffer copy methods for Rust vec
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
/// You need this as dependency in Cargo.toml | |
/// | |
/// [dependencies] | |
/// time = "0.2.26" | |
use std::collections::HashMap; | |
use std::env; | |
use std::ptr; | |
use time::Duration; | |
const SIZE: usize = 10 * 1024 * 1024; | |
fn copy_iter(src: &[u8], dst: &mut Vec<u8>) { | |
for &byte in src { | |
dst.push(byte); | |
} | |
} | |
fn copy_index(src: &[u8], dst: &mut Vec<u8>) { | |
let mut index = 0; | |
unsafe { | |
dst.set_len(SIZE); | |
} | |
while index < src.len() { | |
dst[index] = src[index]; | |
index += 1; | |
} | |
} | |
fn copy_extend(src: &[u8], dst: &mut Vec<u8>) { | |
dst.extend(src); | |
} | |
fn copy_extend_s(src: &[u8], dst: &mut Vec<u8>) { | |
dst.extend_from_slice(src); | |
} | |
fn copy_ptr(src: &[u8], dst: &mut Vec<u8>) { | |
unsafe { | |
dst.set_len(SIZE); | |
ptr::copy_nonoverlapping(src.as_ptr(), (&mut dst[..]).as_mut_ptr(), SIZE); | |
} | |
} | |
fn main() { | |
let max = 100; | |
let mut results: HashMap<&str, i128> = HashMap::new(); | |
let methods = vec!["iter", "index", "ptr", "extend", "extend_s"]; | |
// init map | |
for method in &methods { | |
results.insert(method, 0); | |
} | |
for (method, time) in results.iter_mut() { | |
for _ in 0..max { | |
*time = *time + measure(method); | |
} | |
} | |
for (method, time) in results { | |
let dur = std::time::Duration::from_nanos((time / max) as u64); | |
println!("{:>10} {:>10?}", method, dur); | |
} | |
} | |
fn measure(method: &str) -> i128 { | |
let src = vec![1; SIZE]; | |
let mut dst = Vec::with_capacity(SIZE); | |
let (a, _) = Duration::time_fn(|| match method { | |
"iter" => copy_iter(&src[..], &mut dst), | |
"index" => copy_index(&src[..], &mut dst), | |
"extend_s" => copy_extend_s(&src[..], &mut dst), | |
"ptr" => copy_ptr(&src[..], &mut dst), | |
"extend" => copy_extend(&src[..], &mut dst), | |
m => panic!("Wrong method '{}'", m), | |
}); | |
a.whole_nanoseconds() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I get those results on a Intel i5-9600K (on Windows 10)