1 // `cargo test --benches` and `#[feature(test)]` work only in nightly 2 #![cfg(rustc_nightly)] 3 #![feature(test)] 4 5 extern crate protobuf; 6 extern crate test; 7 8 use std::io; 9 use std::io::Read; 10 11 use protobuf::CodedInputStream; 12 13 use self::test::Bencher; 14 make_bytes(len: usize) -> Vec<u8>15fn make_bytes(len: usize) -> Vec<u8> { 16 let mut r = Vec::with_capacity(len); 17 for i in 0..len { 18 r.push((i % 10) as u8); 19 } 20 test::black_box(r) 21 } 22 23 #[bench] read_byte(b: &mut Bencher)24fn read_byte(b: &mut Bencher) { 25 let v = make_bytes(1_000); 26 b.iter(|| { 27 let mut is = CodedInputStream::from_bytes(test::black_box(&v)); 28 while !is.eof().expect("eof") { 29 test::black_box(is.read_raw_byte().expect("read")); 30 } 31 }); 32 } 33 34 #[bench] read_byte_no_eof(b: &mut Bencher)35fn read_byte_no_eof(b: &mut Bencher) { 36 let v = make_bytes(1_000); 37 b.iter(|| { 38 let mut is = CodedInputStream::from_bytes(test::black_box(&v)); 39 for _ in 0..v.len() { 40 test::black_box(is.read_raw_byte().expect("read")); 41 } 42 assert!(is.eof().expect("eof")); 43 }); 44 } 45 46 #[bench] read_byte_from_vec(b: &mut Bencher)47fn read_byte_from_vec(b: &mut Bencher) { 48 let v = make_bytes(1_000); 49 b.iter(|| { 50 let mut v = io::Cursor::new(test::black_box(&v)); 51 loop { 52 let mut buf = [0]; 53 let count = v.read(&mut buf).expect("read"); 54 if count == 0 { 55 break; 56 } 57 test::black_box(buf); 58 } 59 }); 60 } 61 62 #[bench] read_varint_12(b: &mut Bencher)63fn read_varint_12(b: &mut Bencher) { 64 let mut v = Vec::new(); 65 { 66 let mut v = protobuf::CodedOutputStream::vec(&mut v); 67 for i in 0..1000 { 68 // one or two byte varints 69 v.write_raw_varint32((i * 7919) % (1 << 14)).expect("write"); 70 } 71 v.flush().expect("flush"); 72 } 73 b.iter(|| { 74 let mut is = CodedInputStream::from_bytes(test::black_box(&v)); 75 let mut count = 0; 76 while !is.eof().expect("eof") { 77 test::black_box(is.read_raw_varint32().expect("read")); 78 count += 1; 79 } 80 assert_eq!(1000, count); 81 }) 82 } 83 84 #[bench] read_varint_1(b: &mut Bencher)85fn read_varint_1(b: &mut Bencher) { 86 let mut v = Vec::new(); 87 { 88 let mut v = protobuf::CodedOutputStream::vec(&mut v); 89 for i in 0..1000 { 90 // one or two byte varints 91 v.write_raw_varint32((i * 7919) % (1 << 7)).expect("write"); 92 } 93 v.flush().expect("flush"); 94 } 95 b.iter(|| { 96 let mut is = CodedInputStream::from_bytes(test::black_box(&v)); 97 let mut count = 0; 98 while !is.eof().expect("eof") { 99 test::black_box(is.read_raw_varint32().expect("read")); 100 count += 1; 101 } 102 assert_eq!(1000, count); 103 }) 104 } 105