Skip to content

Commit

Permalink
feat: rework demo
Browse files Browse the repository at this point in the history
Signed-off-by: Martin Kröning <[email protected]>
  • Loading branch information
mkroening committed Apr 10, 2024
1 parent 87a5b8c commit f5a567f
Show file tree
Hide file tree
Showing 8 changed files with 245 additions and 326 deletions.
69 changes: 69 additions & 0 deletions examples/demo/src/fs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use std::path::Path;
use std::{fs, io};

pub fn read_dir(path: &str) -> io::Result<()> {
eprintln!();

assert!(Path::new(path).is_dir());
eprintln!("Reading {path:?} directory entries");
let entries = fs::read_dir(path)?.collect::<Result<Vec<_>, _>>()?;

assert!(!entries.is_empty());
for entry in entries {
let path = entry.path();
eprintln!("Found {path:?}");
}

Ok(())
}

pub fn read_version() -> io::Result<()> {
eprintln!();
let path = "/proc/version";

eprint!("{path} contains");
let version = fs::read_to_string(path).unwrap();
eprintln!(" {version:?}");

Ok(())
}

fn test_file(path: &str) -> io::Result<()> {
let contents = "Hello, world!";

eprint!("{path:15} : writing");
fs::write(path, contents)?;

eprint!(", reading");
let read = fs::read_to_string(path)?;
assert_eq!(contents, read);

// FIXME: this fails on Uhyve
// eprintln!(", deleting");
// fs::remove_file(path)?;

Ok(())
}

pub fn file() -> io::Result<()> {
eprintln!();
test_file("/tmp/hello.txt")?;
if cfg!(target_os = "hermit") && cfg!(feature = "fs") {
test_file("/root/hello.txt")?;
}
Ok(())
}

pub fn dir() -> io::Result<()> {
read_dir("/proc")?;
// FIXME: this fails on both QEMU and Uhyve
// read_dir("/root")?;
Ok(())
}

pub fn fs() -> io::Result<()> {
read_version()?;
file()?;
dir()?;
Ok(())
}
35 changes: 13 additions & 22 deletions examples/demo/src/laplace.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,22 @@
use std::time::Instant;
use std::{thread, vec};
use std::vec;

use rayon::prelude::*;

pub fn laplace(size_x: usize, size_y: usize) -> Result<(), ()> {
let ncpus = thread::available_parallelism().unwrap().get();
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(ncpus)
.build()
.unwrap();
let matrix = matrix_setup(size_x, size_y);
const SIZE: usize = if cfg!(debug_assertions) { 16 } else { 64 };

pub fn laplace() {
eprintln!();

let matrix = matrix_setup(SIZE, SIZE);

eprintln!("Laplace iterations");
let now = Instant::now();
let (iterations, res) = pool.install(|| compute(matrix, size_x, size_y));
println!(
"Time to solve {} s, iterations {}, residuum {}",
now.elapsed().as_secs_f64(),
iterations,
res
);

if res < 0.01 {
Ok(())
} else {
Err(())
}
let (i, residual) = compute(matrix, SIZE, SIZE);
let elapsed = now.elapsed();
eprintln!("{i} iterations: {elapsed:?} (residual: {residual})");

assert!(residual < 0.001);
}

fn matrix_setup(size_x: usize, size_y: usize) -> vec::Vec<vec::Vec<f64>> {
Expand Down Expand Up @@ -97,7 +89,6 @@ fn iteration(cur: &[f64], next: &mut [f64], size_x: usize, size_y: usize) {
});
}

#[inline(never)]
pub fn compute(mut matrix: vec::Vec<vec::Vec<f64>>, size_x: usize, size_y: usize) -> (usize, f64) {
let mut counter = 0;

Expand Down
128 changes: 49 additions & 79 deletions examples/demo/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,90 +1,60 @@
use std::{env, f64, hint, io};

#[cfg(target_os = "hermit")]
use hermit as _;

mod fs;
mod laplace;
mod matmul;
mod tests;
mod thread_local;
mod pi;
mod thread;

fn main() -> io::Result<()> {
hello();
print_env();
arithmetic();
thread::sleep();
thread::spawn()?;
fs::fs()?;
pi::pi();
matmul::matmul();
laplace::laplace();
Ok(())
}

pub fn hello() {
eprintln!();
eprintln!("Hello, Hermit! 🦀");
eprintln!("Hello, world!");
eprintln!("Привет, мир!");
eprintln!("こんにちは世界!");
eprintln!("你好世界!");
eprintln!("สวัสดีชาวโลก!");
eprintln!("Chào thế giới!");
}

use tests::*;
pub fn print_env() {
eprintln!();
eprintln!("Arguments:");
for argument in env::args() {
eprintln!("{argument}");
}

fn test_result<T>(result: Result<(), T>) -> &'static str {
match result {
Ok(_) => "ok",
Err(_) => "failed!",
eprintln!();
eprintln!("Environment variables:");
for (key, value) in env::vars() {
eprintln!("{key}: {value}");
}
}

fn main() {
println!("Test {} ... {}", stringify!(hello), test_result(hello()));
println!(
"Test {} ... {}",
stringify!(sleep),
test_result(test_sleep())
);
println!(
"Test {} ... {}",
stringify!(test_thread_local),
test_result(thread_local::test_thread_local())
);
println!(
"Test {} ... {}",
stringify!(arithmetic),
test_result(arithmetic())
);
println!(
"Test {} ... {}",
stringify!(print_argv),
test_result(print_argv())
);
println!(
"Test {} ... {}",
stringify!(print_env),
test_result(print_env())
);
println!(
"Test {} ... {}",
stringify!(read_file),
test_result(read_file())
);
println!(
"Test {} ... {}",
stringify!(read_dir),
test_result(read_dir())
);
println!(
"Test {} ... {}",
stringify!(create_file),
test_result(create_file())
);
println!(
"Test {} ... {}",
stringify!(threading),
test_result(threading())
);
println!(
"Test {} ... {}",
stringify!(pi_sequential),
test_result(pi_sequential(5000000))
);
println!(
"Test {} ... {}",
stringify!(pi_parallel),
test_result(pi_parallel(5000000))
);
println!(
"Test {} ... {}",
stringify!(laplace),
test_result(laplace::laplace(128, 128))
);
println!(
"Test {} ... {}",
stringify!(test_matmul_strassen),
test_result(matmul::test_matmul_strassen())
);
println!(
"Test {} ... {}",
stringify!(thread_creation),
test_result(thread_creation())
);
pub fn arithmetic() {
eprintln!();

let x = hint::black_box(f64::consts::PI) * 2.0;
let y: f64 = hint::black_box(x).exp();
let z: f64 = hint::black_box(y).ln();

eprintln!("x = {x}");
eprintln!("e^x = {y}");
eprintln!("ln(e^x) = {z}");
}
10 changes: 5 additions & 5 deletions examples/demo/src/matmul.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ fn timed_matmul<F: FnOnce(&[f32], &[f32], &mut [f32])>(size: usize, f: F, name:
f(&a[..], &b[..], &mut dest[..]);
let dur = Instant::now() - start;
let nanos = u64::from(dur.subsec_nanos()) + dur.as_secs() * 1_000_000_000u64;
println!(
eprintln!(
"{}:\t{}x{} matrix: {} s",
name,
size,
Expand All @@ -384,7 +384,9 @@ fn timed_matmul<F: FnOnce(&[f32], &[f32], &mut [f32])>(size: usize, f: F, name:

const SIZE: usize = if cfg!(debug_assertions) { 64 } else { 256 };

pub fn test_matmul_strassen() -> Result<(), ()> {
pub fn matmul() {
eprintln!();
eprintln!("Matrix multiplication");
if SIZE <= 1024 {
// Crappy algorithm takes several minutes on larger inputs.
timed_matmul(SIZE, seq_matmul, "seq row-major");
Expand All @@ -397,7 +399,5 @@ pub fn test_matmul_strassen() -> Result<(), ()> {
let par = timed_matmul(SIZE, matmulz, "par z-order");
timed_matmul(SIZE, matmul_strassen, "par strassen");
let speedup = seq as f64 / par as f64;
println!("speedup: {:.2}x", speedup);

Ok(())
eprintln!("speedup: {:.2}x", speedup);
}
46 changes: 46 additions & 0 deletions examples/demo/src/pi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use std::time::Instant;
use std::{f64, hint};

use rayon::prelude::*;

const STEPS: u64 = if cfg!(debug_assertions) {
50_000
} else {
5_000_000
};
const STEP_SIZE: f64 = 1.0 / STEPS as f64;

#[derive(Debug)]
pub enum Mode {
Sequential,
Parallel,
}

fn calculate_pi(mode: Mode) {
eprintln!();
eprint!("Calculating Pi {:14}", format!("({mode:?}): "));

let steps = hint::black_box(STEPS);
let map_step = |i| {
let x = (i as f64 + 0.5) * STEP_SIZE;
4.0 / (1.0 + x * x)
};

let now = Instant::now();
let sum = match mode {
Mode::Sequential => (0..steps).map(map_step).sum::<f64>(),
Mode::Parallel => (0..steps).into_par_iter().map(map_step).sum::<f64>(),
};
let mypi = sum * STEP_SIZE;
let elapsed = now.elapsed();

eprintln!("{elapsed:?}");

assert!((mypi - f64::consts::PI).abs() < 1e-10);
}

pub fn pi() {
eprintln!();
calculate_pi(Mode::Sequential);
calculate_pi(Mode::Parallel);
}
Loading

0 comments on commit f5a567f

Please sign in to comment.