Last active
March 4, 2019 18:38
-
-
Save cfsamson/84c66e49966814b4d044f2be0ad10d4c to your computer and use it in GitHub Desktop.
Optimizing the code part 3
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
// -------- We change the relevant code in main() from this: -------- | |
fn main() { | |
// {...} | |
let bytes: Vec<u8> = pixels.iter().flat_map(|(y, x)| { | |
let mut color = Vec3::from(0.0); | |
for _ in (0..samples_count).rev() { | |
color = color + trace(position, !(goal + left * (*x - w / 2.0 + random_val()).into() + up * (*y - h / 2.0 + random_val()).into())); | |
} | |
color = color * (1.0 / samples_count as f32).into() + (14.0 / 241.0).into(); | |
let o: Vec3 = color + Vec3::from(1.0); | |
color = Vec3::new_abc(color.x / o.x, color.y / o.y, color.z / o.z) * Vec3::from(255.0); | |
vec![color.x as u8, color.y as u8, color.z as u8] | |
}).collect(); | |
file.write_all(&bytes).unwrap(); | |
} | |
// -------- Into this: -------- | |
use rayon::prelude::*; | |
fn main() { | |
// {...} | |
let bytes: Vec<u8> = pixels.par_iter().flat_map(|(y, x)| { | |
// ^ notice this change | |
let mut color = Vec3::from(0.0); | |
for _ in (0..samples_count).rev() { | |
color = color + trace(position, !(goal + left * (*x - w / 2.0 + random_val()).into() + up * (*y - h / 2.0 + random_val()).into())); | |
} | |
color = color * (1.0 / samples_count as f32).into() + (14.0 / 241.0).into(); | |
let o: Vec3 = color + Vec3::from(1.0); | |
color = Vec3::new_abc(color.x / o.x, color.y / o.y, color.z / o.z) * Vec3::from(255.0); | |
vec![color.x as u8, color.y as u8, color.z as u8] | |
}) | |
.collect(); | |
file.write_all(&bytes).unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment