Sure! Below are two simple concurrent programs in both Elixir (using BEAM VM) and Go (Golang). These programs perform the same basic task: spawning a large number of lightweight workers that do minimal work, simulating concurrency.
We’ll then discuss how to benchmark their memory usage, so you can compare them.
✅ Problem Description
The program will:
Spawn 100,000 concurrent workers.
Each worker sleeps for a short time and exits.
The goal is to see how each language manages high concurrency with respect to memory usage.
🐍 Elixir Version (elixir_concurrency.exs)
elixir
# elixir_concurrency.exs
pid = self()
spawn_workers = fn count ->
Enum.each(1..count, fn _ ->
spawn(fn ->
:timer.sleep(50)
send(pid, :done)
end)
end)
end
# Start workers
spawn_workers.(100_000)
# Wait for all to finish
collect = fn total ->
receive do
:done ->
if total > 1 do
collect.(total - 1)
else
IO.puts("All workers done.")
end
after
5000 ->
IO.puts("Timeout waiting for workers.")
end
end
collect.(100_000)
Run Elixir:
bash
elixir elixir_concurrency.exs
🚀 Go Version (go_concurrency.go)
go
// go_concurrency.go
package main
import (
"fmt"
"sync"
"time"
)
func main() {
const numWorkers = 100000
var wg sync.WaitGroup
for i := 0; i < numWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(50 * time.Millisecond)
}()
}
wg.Wait()
fmt.Println("All workers done.")
}
Build and run Go:
bash
go run go_concurrency.go
🧪 Benchmarking Memory Usage
To measure memory usage, we can use system tools like time, top, or ps. Here's a simple way using /usr/bin/time on Unix-like systems.
Note: You may need to install time if not available by default (on macOS it’s under gtime via Homebrew).
Measure memory with GNU time:
On Linux/macOS (with GNU time):
bash
/usr/bin/time -v elixir elixir_concurrency.exs
/usr/bin/time -v go run go_concurrency.go
You'll get output like:
code
Maximum resident set size (kbytes): XXXXX
This tells you the peak memory used.
📊 Sample Results (Approximate)
Language
Workers
Max RSS Memory
Elixir
100,000
~200 MB
Go
100,000
~400–600 MB
⚠️ This is approximate and depends on your system and Go/Erlang versions.
Why the Difference?
Elixir processes are green threads/lightweight (~300 bytes per process).
Go goroutines start at ~2KB but grow as needed, and scheduling overhead + stack allocations make them heavier than Erlang processes in high numbers.
📈 Tips for Accurate Measurement
Run both programs on the same machine/environment.
Use htop or top to observe real-time memory usage.
Ensure no other heavy processes are running during benchmarking.
Try varying the number of workers (e.g., 10k, 100k, 1M) to observe scaling behavior.
🧠 Summary
Feature
Elixir (BEAM)
Go (Goroutines)
Concurrency model
Lightweight processes (BEAM VM)
Goroutines (runtime-managed)
Default stack size
~300 bytes
~2KB (grows dynamically)
Memory efficiency
High
Moderate
Tooling
Good with observer
Good with pprof
Would you like me to generate a script to automate this comparison and graph the results?