Skip to content

Instantly share code, notes, and snippets.

@ggggggggg
Created June 30, 2015 16:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggggggggg/c93a0f029620deca4f2e to your computer and use it in GitHub Desktop.
Save ggggggggg/c93a0f029620deca4f2e to your computer and use it in GitHub Desktop.
Some go vs julia concurrency comparisons
package main
import "time"
import "fmt"
func counter(c chan int, N int) {
for j := 1; j <= N; j++ {
c <- j
}
}
func main() {
const N=100000
var a [N]int
start := time.Now()
for j := 1; j <= N; j++ {
a[j-1] = j
}
elapsed := time.Since(start)
fmt.Println(elapsed)
c := make(chan int)
go counter(c,N)
var b [N]int
start2 := time.Now()
for j := 1; j <= N; j++ {
b[j-1] = <-c
}
elapsed2 := time.Since(start2)
fmt.Println(elapsed2)
fmt.Println(b == a)
}
686go2:golang oneilg$ ./chan_bench
86.473µs
33.049905ms
true
type GoChannel{T}
v::T
hasvalue::Bool
c::Condition
end
GoChannel(T::DataType) = GoChannel(zero(T), false, Condition())
function Base.put!{T}(c::GoChannel{T}, v::T)
c.hasvalue && wait(c.c)
c.hasvalue = true
c.v=v
notify(c.c)
end
function Base.take!(c::GoChannel)
!c.hasvalue && wait(c.c)
c.hasvalue = false
v=c.v
notify(c.c)
v
end
hasvalue(c::GoChannel) = c.hasvalue
c = GoChannel(Int)
put!(c,1)
@assert take!(c)==1
@assert hasvalue(c) == false
function make_counter(n)
function count(c)
for i =1:n
put!(c,i)
end
end
c = GoChannel(Int)
@schedule count(c)
c
end
counter = make_counter(2)
@assert take!(counter) == 1
sleep(0.001)
@assert take!(counter) == 2
@assert hasvalue(counter)==false
function benchgo(n)
c = make_counter(n)
a = zeros(Int, n)
@time @inbounds for i =1:n
a[i]=take!(c)
end
a
end
function make_counter_produce(n)
function count()
for i=1:n
produce(i)
end
end
Task(count)
end
function benchproduce(n)
c = make_counter_produce(n)
a = zeros(Int, n)
@time @inbounds for i = 1:n
a[i]=consume(c)
end
a
end
function make_counter_rr(n)
function count(r)
for i=1:n
put!(r,i)
end
end
r = RemoteRef()
@schedule count(r)
r
end
function bench_rr(n)
c = make_counter_rr(n)
a = zeros(Int,n)
@time @inbounds for i = 1:n
a[i] = take!(c)
end
a
end
function benchnormal(n)
a = zeros(Int,n)
@time @inbounds for i = 1:n
a[i]=i
end
a
end
n=10^5
benchgo(n);
benchproduce(n);
bench_rr(n);
benchnormal(n);
after running each function once
julia> a=benchgo(n);
elapsed time: 0.412629979 seconds (35623220 bytes allocated, 13.33% gc time)
julia> b=benchproduce(n);
elapsed time: 0.213708174 seconds (3184376 bytes allocated)
julia> c=bench_rr(n);
elapsed time: 0.793898845 seconds (79145592 bytes allocated, 6.47% gc time)
julia> d=benchnormal(n);
elapsed time: 4.0246e-5 seconds (0 bytes allocated)
julia> a==b && a==c && a==d
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment