forked from tablespoon/fun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpi
executable file
·52 lines (46 loc) · 1.51 KB
/
cpi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/bin/bash
LIMIT_METHOD=duration # set this to "quantity" or "duration"
#LIMIT_METHOD=quantity # set this to "quantity" or "duration"
TRIAL_LIMIT=100 # number of trials to evaluate (per core) if LIMIT_METHOD==quantity
DURATION_LIMIT=15 # duration in seconds to run if LIMIT_METHOD==duration
CACHE_SIZE=1200 # number of trials to cache before flushing to bc -- used for tuning; 1000 seems near-optimal
SCALE=10 # scale for bc
PROCS=$(grep -c "^processor[[:space:]]\+:" /proc/cpuinfo)
calc() {
case $1 in
quantity)
while [[ ${counter} -lt ${TRIAL_LIMIT} ]]; do
string+="(${RANDOM}/32768)^2+(${RANDOM}/32768)^2<=1;"
if [[ $(( ++counter % CACHE_SIZE )) -eq 0 ]]; then
echo "$(bc -l <<<"scale=${SCALE};${string}" | grep -c 1):${CACHE_SIZE}"
unset string
fi
done
;;
duration)
while [[ ${SECONDS} -lt ${DURATION_LIMIT} ]]; do
string+="(${RANDOM}/32767)^2+(${RANDOM}/32767)^2<=1;"
if [[ $(( ++counter % CACHE_SIZE )) -eq 0 ]]; then
echo "$(bc -l <<<"scale=${SCALE};${string}" | grep -c 1):${CACHE_SIZE}"
unset string
fi
done
;;
*)
break
;;
esac
[[ -n "${string}" ]] && echo "$(bc -l <<<"scale=${SCALE};${string}" | grep -c 1):$(( counter % CACHE_SIZE ))"
}
parallelCalc() {
for (( proc=0; ${proc} < ${PROCS}; proc++ )); do
calc ${LIMIT_METHOD} &
done
wait
}
for result in $(parallelCalc); do
((results+=${result%:*}))
((trials+=${result#*:}))
done
echo -ne "Trial count: ${trials}\nPi estimate: "
bc -l <<<"scale=${SCALE};${results}/(${trials})*4" | sed "s/0\+$//"