0

That works fine in iex console:

iex(1)> spawn(fn -> :timer.tc(:timer, :sleep, [100]) |> elem(0) |> IO.puts end) #PID<0.106.0> 100603

But when I put exactly the same line spawn(fn -> :timer.tc(:timer, :sleep, [100]) |> elem(0) |> IO.puts end) inside .exs script - nothing happens, no output at all.

Why is that? How can I measure function's execute time in parallel?

gatorex
  • 3
  • 3
  • Why do you need to do it in parallel? And how it supposed to work? Why [this](https://stackoverflow.com/a/29674651/2501279) approach is not suitable for you? – Guru Stron May 17 '20 at 14:23
  • @GuruStron why OP needs to do it in parallel is completely out of the scope of the original question. Also, benchmarks and telemetry have absolutely different applications, and this question is surely more about [`telemetry`](https://hexdocs.pm/telemetry/index.html). – Aleksei Matiushkin May 17 '20 at 14:34

1 Answers1

1

The script exits before this gets printed and you do not monitor the started process, which results in kinda race condition. In fact, everything works as expected. Make sure your script waits for the spawned process to finish (the proper way would be use Task, but this is OK for PoC:

# test.exs
spawn(fn ->
  :timer
  |> :timer.tc(:sleep, [100])
  |> elem(0)
  |> IO.puts()
end)
Process.sleep(1_000)

Proper solution:

# test.exs
task = Task.async(fn ->
  :timer
  |> :timer.tc(:sleep, [100])
  |> elem(0)
  |> IO.puts()
end)
Task.await(task) # this prevents ErlangVM from immediate exit
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • Great, thanks, that works :) Now I can spawn several processes, save to list and run Task.await on every task. – gatorex May 17 '20 at 14:43
  • Of course, it works. To await several tasks one might use [`Task.yield_many/2`](https://hexdocs.pm/elixir/Task.html#yield_many/2) instead. – Aleksei Matiushkin May 17 '20 at 14:47