Skip to content

Instantly share code, notes, and snippets.

Created September 10, 2016 13:07
Show Gist options
  • Save anonymous/c2ff69fd6c70b70cfa6ccb6dc96ffb20 to your computer and use it in GitHub Desktop.
Save anonymous/c2ff69fd6c70b70cfa6ccb6dc96ffb20 to your computer and use it in GitHub Desktop.
defmodule Chain do
def counter(next_pid) do
receive do
n ->
send next_pid, n + 1
end
end
def create_processes(n) do
Enum.reduce 1..n, self,
fn (_, send_to) ->
spawn(Chain, :counter, [send_to])
end
end
def run_calculations(last) do
send last, 0
receive do
answer -> answer
end
end
def run(n) do
last = create_processes(n)
{t, v} = :timer.tc(Chain, :run_calculations, [last])
IO.puts "#{v}, #{t/1_000}"
end
end
package main
import (
"fmt"
"os"
"strconv"
"time"
)
func main() {
n, _ := strconv.Atoi(os.Args[1])
var inChan, outChan chan int
start := make(chan int)
outChan = start
for i := 0; i < n; i++ {
inChan, outChan = outChan, make(chan int)
go fun(inChan, outChan)
}
t := time.Now()
start <- 0
v := <-outChan
fmt.Println(v, time.Now().Sub(t))
}
func fun(in, out chan int) {
c := <-in
out <- (c + 1)
}
#!/usr/bin/env bash
echo Elixir
elixir -r chain.exs -e "Chain.run($1)"
echo Go
go run chain.go $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment