Skip to content

Commit

Permalink
Add Julia implementation using OhMyThreads.jl
Browse files Browse the repository at this point in the history
  • Loading branch information
giordano committed Nov 27, 2024
1 parent fc92267 commit bdd72c1
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions julia_ohmythreads_pi_dir/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Manifest.toml
6 changes: 6 additions & 0 deletions julia_ohmythreads_pi_dir/Project.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[deps]
OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5"

[compat]
OhMyThreads = "0.7"
julia = "1.10"
48 changes: 48 additions & 0 deletions julia_ohmythreads_pi_dir/pi.jl
Original file line number Diff line number Diff line change
@@ -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)
7 changes: 7 additions & 0 deletions julia_ohmythreads_pi_dir/run.sh
Original file line number Diff line number Diff line change
@@ -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 "${@}"

0 comments on commit bdd72c1

Please sign in to comment.