Last active
November 9, 2019 06:27
-
-
Save amoghmargoor/719751ff7ca164232b92258eecfc74aa to your computer and use it in GitHub Desktop.
Rust program for checking performance of Iterators
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 rand; | |
use rand::Rng; | |
use std::io::BufWriter; | |
use std::io::Write; | |
use std::fs::OpenOptions; | |
use std::fs::File; | |
use std::str::FromStr; | |
use std::io::BufReader; | |
use std::io::BufRead; | |
use std::string::String; | |
use std::str::from_utf8; | |
use std::time::Instant; | |
fn main() { | |
let filename : String = String::from_str("/tmp/rand.txt") | |
.expect("unable to create string"); | |
let mut buffer : [i32; 10000] = read_from_file(filename); | |
let coefficients: [i64; 12] = [34, 45, 56, 78, 90, 32, 12, 13, 45, 56, 89, 67]; | |
let qlp_shift: i16 = 0; | |
/** | |
* ********************************************** | |
* Only measuring the performance of below loop. | |
* ********************************************** | |
*/ | |
let now = Instant::now(); | |
for i in 12..buffer.len() { | |
let prediction = coefficients.iter() | |
.zip(&buffer[i - 12..i]) | |
.map(|(&c, &s)| c * s as i64) | |
.sum::<i64>() >> 32; | |
let delta = buffer[i]; | |
buffer[i] = prediction as i32 + delta; | |
} | |
println!("Elapsed time: {}", now.elapsed().as_nanos()) | |
} | |
fn read_from_file(fname : String) -> [i32; 10000] { | |
let file = File::open(fname) | |
.expect("Could not open file"); | |
let mut array= [0; 10000]; | |
let mut reader = BufReader::new(file); | |
let mut buf = vec![]; | |
let mut num_bytes = reader.read_until(b' ', &mut buf) | |
.expect("Cursor read should not fail"); | |
let mut i = 0; | |
while num_bytes != 0 { | |
let int_str: &str = from_utf8(buf.as_slice()) | |
.expect("unable to create string") | |
.trim(); | |
if !int_str.is_empty() { | |
array[i] = int_str.parse::<i32>().expect(&format!("int_str cannot be parsed into digit {} ", int_str)); | |
i = i+1; | |
} | |
buf.clear(); | |
num_bytes = reader.read_until(b' ', &mut buf) | |
.expect("Cursor read should not fail"); | |
} | |
assert_eq!(array.len(), 10000); | |
array | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment