Skip to content

Commit bdd72c1

Browse files
committed
Add Julia implementation using OhMyThreads.jl
1 parent fc92267 commit bdd72c1

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed

julia_ohmythreads_pi_dir/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Manifest.toml

julia_ohmythreads_pi_dir/Project.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[deps]
2+
OhMyThreads = "67456a42-1dca-4109-a031-0a68de7e3ad5"
3+
4+
[compat]
5+
OhMyThreads = "0.7"
6+
julia = "1.10"

julia_ohmythreads_pi_dir/pi.jl

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env julia
2+
3+
using Pkg
4+
Pkg.activate(@__DIR__)
5+
Pkg.resolve()
6+
Pkg.instantiate()
7+
8+
using Base.Threads: nthreads
9+
using OhMyThreads: tmapreduce
10+
11+
function _picalc(numsteps)
12+
slice = 1 / numsteps
13+
14+
return tmapreduce(+, 1:numsteps; ntasks=nthreads()) do i
15+
4.0 / (1.0 + ((i - 0.5) * slice) ^ 2)
16+
end * slice
17+
end
18+
19+
function picalc(numsteps)
20+
21+
println("Calculating PI using:")
22+
println(" ", numsteps, " slices")
23+
println(" ", nthreads(), " thread(s)")
24+
25+
start = time()
26+
mypi = _picalc(numsteps)
27+
elapsed = time() - start
28+
29+
println("Obtained value of PI: ", mypi)
30+
println("Time taken: ", round(elapsed; digits=3), " seconds")
31+
32+
end
33+
34+
numsteps = if length(ARGS) > 0
35+
parse(Int, ARGS[1])
36+
else
37+
1_000_000_000
38+
end
39+
40+
# Warm up kernel
41+
print(" Warming up...")
42+
warms = time()
43+
_picalc(10)
44+
warmt = time() - warms
45+
println("done. [", round(warmt; digits=3), "s]\n")
46+
47+
# Run the full example
48+
picalc(numsteps)

julia_ohmythreads_pi_dir/run.sh

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#!/usr/bin/env bash
2+
3+
if [[ -z "${JULIA_NUM_THREADS}" ]]; then
4+
export JULIA_NUM_THREADS="${OMP_NUM_THREADS:-1}"
5+
fi
6+
7+
julia pi.jl "${@}"

0 commit comments

Comments
 (0)