Here are two simple concurrent programs in Elixir and Go that compute the sum of numbers from 1 to N across multiple tasks, along with memory usage benchmarking instructions:
Elixir Program
elixir
defmodule Benchmark do
def run(m, n) do
# Print memory before starting
IO.puts("Before: #{inspect(:erlang.memory())}")
tasks = for _ <- 1..m, do: Task.async(fn -> compute(n) end)
results = Enum.map(tasks, &Task.await/1)
total = Enum.sum(results)
# Print memory after computation
IO.puts("After: #{inspect(:erlang.memory())}")
total
end
# Efficient sum of 1..n using arithmetic formula (O(1))
defp compute(n), do: n * (n + 1) / 2
end
# Run with 100 tasks, each computing sum(1..1_000_000)
Benchmark.run(100, 1_000_000)
Go Program
go
package main
import (
"fmt"
"runtime"
"sync"
)
func compute(n int) int {
sum := 0
for i := 1; i <= n; i++ {
sum += i
}
return sum
}
func main() {
m := 100
n := 1_000_000
var wg sync.WaitGroup
results := make(chan int, m)
// Print memory before starting
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
fmt.Printf("Before: %v bytes allocated\n", mem.Alloc)
for i := 0; i < m; i++ {
wg.Add(1)
go func() {
defer wg.Done()
results <- compute(n)
}()
}
wg.Wait()
close(results)
// Print memory after computation
runtime.ReadMemStats(&mem)
fmt.Printf("After: %v bytes allocated\n", mem.Alloc)
var total int
for res := range results {
total += res
}
fmt.Println("Total:", total)
}
How to Run and Benchmark
Elixir
Save the Elixir code to a file (e.g., benchmark.exs).
Run it with:
bash
elixir benchmark.exs
The output will show memory usage before and after the computation. Look for differences in the :processes and :system memory categories.
Go
Save the Go code to a file (e.g., main.go).
Run it with:
bash
go run main.go
The output will show the allocated memory before and after the computation.
Key Observations
Elixir:
Uses lightweight processes (managed by the BEAM VM).
Memory includes process overhead (e.g., :processes in :erlang.memory()).
The compute function uses O(1) memory (thanks to the arithmetic formula).
Go:
Uses goroutines (lightweight threads managed by Go's runtime).
Memory is tracked via runtime.MemStats.Alloc, which shows total allocated bytes.
Typical Results
Elixir:
Processes have higher per-task overhead (~KB per process) but are safe for millions of tasks.
Memory usage grows linearly with the number of tasks.
Go:
Goroutines have lower overhead (~~1KB per goroutine initially).
Memory usage is generally lower for the same number of concurrent tasks.
Notes
Elixir:
Use :erlang.memory() to see memory categories like :processes, :system, and :ets.
For deeper analysis, use tools like :observer.start() or erlgrind.
Go:
Use pprof for detailed profiling:
bash
go tool pprof http://localhost:6060/debug/pprof/heap
Both languages excel at concurrency, but Elixir's processes are more memory-intensive per task compared to Go's goroutines. The choice depends on your use case and scalability needs!