I compiled a multithreaded version that runs the calculation twice using ‘spawn’ and ‘-Dpreview_mt’, in order to test whether CPU-intensive tasks can be accelerated by ‘spawn’. The result was that compared to synchronous computation once, the multithreaded computation twice did not improve efficiency. However, the CPU utilization did indeed exceed 100%.
channel = Channel(UInt32).new
def fib(n : UInt32) : UInt32
if n <= 1
n
else
fib(n-1) + fib(n-2)
end
end
number = ARGV[0].to_u32
spawn do
channel.send(fib(number))
end
spawn do
channel.send(fib(number))
end
res_1 = channel.receive
res_2 = channel.receive
puts "#{res_1} #{res_2}"
time -v
output:
[I] ~/d/crystal ❯❯❯ gtime ./hello_twice.exe 42
267914296 267914296
12.51user 0.07system 0:06.95elapsed 181%CPU (0avgtext+0avgdata 2136maxresident)k
0inputs+0outputs (0major+665minor)pagefaults 0swaps
[I] ~/d/crystal ❯❯❯ gtime ./hello.exe 42
267914296
4.95user 0.47system 0:06.02elapsed 90%CPU (0avgtext+0avgdata 1868maxresident)k
0inputs+0outputs (3major+591minor)pagefaults 0swaps