diff --git a/Chapter09/Cargo.toml b/Chapter09/Cargo.toml index a0acf01..f2608b0 100644 --- a/Chapter09/Cargo.toml +++ b/Chapter09/Cargo.toml @@ -5,6 +5,7 @@ version = "1.0.0" [dependencies] flame = "0.2" rand = "0.4.2" +requests = "0.0.30" [[bin]] name = "performance_release_mode" @@ -33,3 +34,11 @@ path = "performance_profiling3.rs" [[bin]] name = "performance_profiling4" path = "performance_profiling4.rs" + +[[bin]] +name = "performance_constant" +path = "performance_constant.rs" + +[[bin]] +name = "performance_logarithmic" +path = "performance_logarithmic.rs" diff --git a/Chapter09/performance_constant.rs b/Chapter09/performance_constant.rs new file mode 100644 index 0000000..9271787 --- /dev/null +++ b/Chapter09/performance_constant.rs @@ -0,0 +1,29 @@ +fn allocate() -> [u64; 1000] { + [22; 1000] +} + +fn flop(x: f64, y: f64) -> f64 { + x * y +} + +fn lookup(x: &[u64; 1000]) -> u64 { + x[234] * x[345] +} + +fn main() { + let mut data = allocate(); + for _ in 0..1000 { + //constant size memory allocation + data = allocate(); + } + + for _ in 0..1000000 { + //reference data + lookup(&data); + } + + for _ in 0..1000000 { + //floating point operation + flop(2.0, 3.0); + } +} diff --git a/Chapter09/performance_logarithmic.rs b/Chapter09/performance_logarithmic.rs new file mode 100644 index 0000000..683b38c --- /dev/null +++ b/Chapter09/performance_logarithmic.rs @@ -0,0 +1,41 @@ +extern crate rand; +extern crate flame; +use std::fs::File; + +fn main() { + + let mut data = vec![0; 1000]; + for di in 0..data.len() { + data[di] = rand::random::(); + } + + flame::start("sort n=1000"); + data.sort(); + flame::end("sort n=1000"); + + flame::start("binary search n=1000 100 times"); + for _ in 0..100 { + let c = rand::random::(); + data.binary_search(&c).ok(); + } + flame::end("binary search n=1000 100 times"); + + let mut data = vec![0; 10000]; + for di in 0..data.len() { + data[di] = rand::random::(); + } + + flame::start("sort n=10000"); + data.sort(); + flame::end("sort n=10000"); + + flame::start("binary search n=10000 100 times"); + for _ in 0..100 { + let c = rand::random::(); + data.binary_search(&c).ok(); + } + flame::end("binary search n=10000 100 times"); + + flame::dump_html(&mut File::create("flame-graph.html").unwrap()).unwrap(); + +}