From bdd72c150a5f2b45465f4b5b2448296d9368c283 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mos=C3=A8=20Giordano?= Date: Tue, 26 Nov 2024 20:35:09 -0500 Subject: [PATCH] Add Julia implementation using `OhMyThreads.jl` --- julia_ohmythreads_pi_dir/.gitignore | 1 + julia_ohmythreads_pi_dir/Project.toml | 6 ++++ julia_ohmythreads_pi_dir/pi.jl | 48 +++++++++++++++++++++++++++ julia_ohmythreads_pi_dir/run.sh | 7 ++++ 4 files changed, 62 insertions(+) create mode 100644 julia_ohmythreads_pi_dir/.gitignore create mode 100644 julia_ohmythreads_pi_dir/Project.toml create mode 100755 julia_ohmythreads_pi_dir/pi.jl create mode 100755 julia_ohmythreads_pi_dir/run.sh diff --git a/julia_ohmythreads_pi_dir/.gitignore b/julia_ohmythreads_pi_dir/.gitignore new file mode 100644 index 0000000..ba39cc5 --- /dev/null +++ b/julia_ohmythreads_pi_dir/.gitignore @@ -0,0 +1 @@ +Manifest.toml diff --git a/julia_ohmythreads_pi_dir/Project.toml b/julia_ohmythreads_pi_dir/Project.toml new file mode 100644 index 0000000..d64665c --- /dev/null +++ b/julia_ohmythreads_pi_dir/Project.toml @@ -0,0 +1,6 @@ +[deps] +OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5" + +[compat] +OhMyThreads = "0.7" +julia = "1.10" diff --git a/julia_ohmythreads_pi_dir/pi.jl b/julia_ohmythreads_pi_dir/pi.jl new file mode 100755 index 0000000..4e48121 --- /dev/null +++ b/julia_ohmythreads_pi_dir/pi.jl @@ -0,0 +1,48 @@ +#!/usr/bin/env julia + +using Pkg +Pkg.activate(@__DIR__) +Pkg.resolve() +Pkg.instantiate() + +using Base.Threads: nthreads +using OhMyThreads: tmapreduce + +function _picalc(numsteps) + slice = 1 / numsteps + + return tmapreduce(+, 1:numsteps; ntasks=nthreads()) do i + 4.0 / (1.0 + ((i - 0.5) * slice) ^ 2) + end * slice +end + +function picalc(numsteps) + + println("Calculating PI using:") + println(" ", numsteps, " slices") + println(" ", nthreads(), " thread(s)") + + start = time() + mypi = _picalc(numsteps) + elapsed = time() - start + + println("Obtained value of PI: ", mypi) + println("Time taken: ", round(elapsed; digits=3), " seconds") + +end + +numsteps = if length(ARGS) > 0 + parse(Int, ARGS[1]) +else + 1_000_000_000 +end + +# Warm up kernel +print(" Warming up...") +warms = time() +_picalc(10) +warmt = time() - warms +println("done. [", round(warmt; digits=3), "s]\n") + +# Run the full example +picalc(numsteps) diff --git a/julia_ohmythreads_pi_dir/run.sh b/julia_ohmythreads_pi_dir/run.sh new file mode 100755 index 0000000..b4ca7f9 --- /dev/null +++ b/julia_ohmythreads_pi_dir/run.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +if [[ -z "${JULIA_NUM_THREADS}" ]]; then + export JULIA_NUM_THREADS="${OMP_NUM_THREADS:-1}" +fi + +julia pi.jl "${@}"