Skip to content

Instantly share code, notes, and snippets.

@fschutt
Created February 18, 2018 01:31
Show Gist options
  • Save fschutt/d952b3344b3ddf33b2a2b4c386b19291 to your computer and use it in GitHub Desktop.
Save fschutt/d952b3344b3ddf33b2a2b4c386b19291 to your computer and use it in GitHub Desktop.
extern crate itoa;
extern crate smallvec;
macro_rules! print_time {
($start:expr, $end:expr) => (println!("time: {} ns", ($end - $start).subsec_nanos() as f32 / 1_000_000.0);)
}
// 189 ns
fn new_order_slow(stock: &str, price: i32, quantity: i32) -> String {
format!("NEW {} {} {}", stock, price, quantity)
}
// 117 ns
fn new_order_fast(stock: &str, price: i32, quantity: i32) -> String {
let mut s = Vec::<u8>::with_capacity(stock.len() + 6);
s.extend_from_slice(b"NEW ");
s.extend_from_slice(stock.as_bytes());
s.push(b' ');
itoa::write(&mut s, price).unwrap();
s.push(b' ');
itoa::write(&mut s, quantity).unwrap();
unsafe { String::from_utf8_unchecked(s) }
}
// 78 ns
fn new_order_faster(stock: &str, price: i32, quantity: i32) -> String {
use smallvec::SmallVec;
let mut s = SmallVec::<[u8; 32]>::new();
s.extend_from_slice(b"NEW ");
s.extend_from_slice(stock.as_bytes());
s.push(b' ');
itoa::write(&mut s, price).unwrap();
s.push(b' ');
itoa::write(&mut s, quantity).unwrap();
unsafe { String::from_utf8_unchecked(s.to_vec()) }
}
fn main() {
{
println!("new_order_slow:");
let mut last = String::new();
let time_start = ::std::time::Instant::now();
for i in 0..1_000_000 {
last = new_order_slow("NVDA", i, i);
}
let time_end = ::std::time::Instant::now();
println!("last: {}", last);
print_time!(time_start, time_end);
}
{
println!("new_order_fast:");
let mut last = String::new();
let time_start = ::std::time::Instant::now();
for i in 0..1_000_000 {
last = new_order_fast("NVDA", i, i);
}
let time_end = ::std::time::Instant::now();
println!("last: {}", last);
print_time!(time_start, time_end);
}
{
println!("new_order_faster:");
let mut last = String::new();
let time_start = ::std::time::Instant::now();
for i in 0..1_000_000 {
last = new_order_faster("NVDA", i, i);
}
let time_end = ::std::time::Instant::now();
println!("last: {}", last);
print_time!(time_start, time_end);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment