From f16175eeee3b4709876207a776f93398b076d01f Mon Sep 17 00:00:00 2001 From: Ishan Jain Date: Thu, 11 Jan 2024 03:34:28 +0530 Subject: [PATCH] minor optimizations --- src/main.rs | 51 ++++++++++++++++++++++++++------------------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/src/main.rs b/src/main.rs index f04ee14..8454c85 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,12 +24,12 @@ fn main() { continue; } - let loc = if line[l - 4] == b';' { - l - 4 + let loc = if line[l - 6] == b';' { + l - 6 } else if line[l - 5] == b';' { l - 5 - } else if line[l - 6] == b';' { - l - 6 + } else if line[l - 4] == b';' { + l - 4 } else { unreachable!(); }; @@ -39,34 +39,34 @@ fn main() { let val = parse_float(val); - let (min, sum, max, counter) = - map.entry(city) - .or_insert((std::f32::MAX, 0.0, std::f32::MIN, 0)); + let (min, sum, max, counter) = map + .entry(city) + .or_insert_with(|| (std::i16::MAX, 0, std::i16::MIN, 0)); *min = val.min(*min); *max = val.max(*max); *counter += 1; - *sum += val; + *sum += val as i32; } let t2_elapsed = t2.elapsed(); let t3 = Instant::now(); - let mut list: Vec<(&[u8], (f32, f32, f32, usize))> = map.into_iter().collect(); + let mut list: Vec<(&[u8], (i16, i32, i16, usize))> = map.into_iter().collect(); list.sort_unstable_by(|(a, _), (b, _)| a.cmp(b)); let mut output = String::new(); let l = list.len(); - for (i, (city, (min, mean, max, counter))) in list.into_iter().enumerate() { + for (i, (city, (min, sum, max, counter))) in list.into_iter().enumerate() { output.push_str(&format!( "{}={:.1}/{:.1}/{:.1}{}", String::from_utf8_lossy(city), - min, - mean / counter as f32, - max, + (min as f32 / 10.0), + (sum as f32 / 10.0) / counter as f32, + (max as f32 / 10.0), if i == l - 1 { "" } else { ", " } )); } @@ -82,30 +82,31 @@ fn main() { } #[inline] -fn parse_float(b: &[u8]) -> f32 { +fn parse_float(b: &[u8]) -> i16 { let l = b.len(); - let mut num: i32 = 0; + let mut num: i16 = 0; let mut is_negative = false; - for &c in b.iter().take_while(|&&x| x != b'.') { - match c { + let mut i = 0; + while unsafe { *b.get_unchecked(i) } != b'.' { + match unsafe { *b.get_unchecked(i) } { v @ b'0'..=b'9' => { num *= 10; - num += (v - b'0') as i32; + num += (v - b'0') as i16; } b'-' => is_negative = true, - b'.' => continue, - - _ => unreachable!(), + b'.' => break, + _ => (), } + i += 1; } - let mut num = num as f32; + num *= 10; + num += (b[l - 1] - b'0') as i16; - num += 0.1 * (b[l - 1] - b'0') as f32; if is_negative { - num *= -1.0; + num *= -1; } - num * 10.0 / 10.0 + num }