Skip to content

Instantly share code, notes, and snippets.

@garyyu
Last active August 22, 2018 02:40
Show Gist options
  • Save garyyu/05231bd2c09fd561729e89cffd45a0d4 to your computer and use it in GitHub Desktop.
Save garyyu/05231bd2c09fd561729e89cffd45a0d4 to your computer and use it in GitHub Desktop.
BufStream Test
extern crate bufstream;
use std::net::{TcpListener, TcpStream};
use bufstream::BufStream;
use std::io::{BufReader, Write, Read};
use std::thread;
//use std::str;
fn main() {
const LOOPS: usize = 100_000;
const U8SIZE: usize = 10;
let listener = TcpListener::bind("127.0.0.1:8080")
.expect("listen failed");
thread::spawn(move || {
for stream in listener.incoming() {
let mut stream = stream.unwrap();
thread::spawn(move || {
for x in 0..LOOPS {
stream.write_all(format!("{:0>9}\n", x).as_bytes())
.expect("write failed");
}
});
}
});
// TcpStream
let start_a = std::time::Instant::now();
{
let stream_a = TcpStream::connect("127.0.0.1:8080")
.expect("connect_b failed");
let mut br = BufReader::new(stream_a);
let mut s:[u8; U8SIZE] = [0; U8SIZE];
while br.read(&mut s).unwrap_or(0) > 0 {
//print!("{}", str::from_utf8(&s).unwrap());
}
}
let end_a = std::time::Instant::now();
let start_b = std::time::Instant::now();
{
let mut stream_b = TcpStream::connect("127.0.0.1:8080")
.expect("connect_b failed");
let mut s:[u8; U8SIZE] = [0; U8SIZE];
while stream_b.read(&mut s).unwrap_or(0) > 0 {
//print!("{}", str::from_utf8(&s).unwrap());
}
}
let end_b = std::time::Instant::now();
// BufStream
let start_c = std::time::Instant::now();
{
let stream_c = TcpStream::connect("127.0.0.1:8080")
.expect("connect_c failed");
let mut buf = BufStream::new(stream_c);
let mut s:[u8; U8SIZE] = [0; U8SIZE];
while buf.read(&mut s).unwrap_or(0) > 0 {
//print!("{}", str::from_utf8(&s).unwrap());
}
}
let end_c = std::time::Instant::now();
let dur_a = end_a - start_a;
let dur_b = end_b - start_b;
let dur_c = end_c - start_c;
println!("TcpStream with BufReader()\ttook {:?}", dur_a);
println!("TcpStream with Read()\t\ttook {:?}", dur_b);
println!();
println!("BufStream with Read()\t\ttook {:?}", dur_c);
}
[package]
name = "bufstream-test"
version = "0.1.0"
authors = ["Gary Yu <gairy.yu@gmail.com>"]
[dependencies]
bufstream = "0.1.3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment