Created
January 14, 2016 00:32
-
-
Save isagalaev/3d6c2f68a44f1ac27028 to your computer and use it in GitHub Desktop.
Copying memory
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
extern crate time; | |
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_push_all(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 args: Vec<_> = env::args().collect(); | |
if args.len() < 2 { | |
panic!("Provide method") | |
} | |
let src = vec![1; SIZE]; | |
let mut dst = Vec::with_capacity(SIZE); | |
println!("{}", Duration::span(|| { | |
match &(args[1])[..] { | |
"iter" => copy_iter(&src[..], &mut dst), | |
"index" => copy_index(&src[..], &mut dst), | |
"push_all" => copy_push_all(&src[..], &mut dst), | |
"ptr" => copy_ptr(&src[..], &mut dst), | |
_ => println!("Wrong method"), | |
} | |
})); | |
println!("{:?}", &dst[..10]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment