I've just solved the #12 problem in Project Euler, about divisor and triangle number, once in Go and once in JavaScript. I thought the code in Go would be much faster than one in JS, cause JS runs the code in runtime and Go builds the code. I know that building the code doesn't directly mean good performance, but the result was that even the code in JS was sometimes faster in different conditions.
The code I used is like below.
https://gist.github.com/noraesae/675e40477e177f9f63f9
I tested them in my macbook, and spec is like below.
Processor: 2.6 GHz Intel Core i5
Memory: 8 GB 1600 MHz DDR3
I ran them with commands below.
$ #js
$ node euler12.js$ #go
$ go build euler12.go
$ ./euler12
Did I do something wrong? If not, why there's no difference between them? I also tested with Python and there was a big gap between Go and Python. Thanks in advance.
Pretty interesting, on my machine (macbookpro late 2013, i7 2.3ghz), the JS code is much faster than the Go one:
JS:
time node test.js
842161320
real 0m4.437s
user 0m4.900s
sys 0m0.150s
Go:
time GOMAXPROCS=8 ./test
842161320
real 0m7.345s
user 0m7.470s
sys 0m0.010s
However, after a quick optimization of the Go code:
Go:
time GOMAXPROCS=8 ./test
842161320
real 0m1.760s
user 0m11.610s
sys 0m0.230s
The quick optimization I am talking about (very naive): parallelize your computation:
package main
import (
"fmt"
"os"
"runtime"
)
func numberOfDevisor(n int64) int64 {
var result int64
var i int64 = 1
for true {
if n%i == 0 {
opposite := n / i
if opposite == i {
result++
return result
} else if opposite > i {
result += 2
} else {
return result
}
}
i++
}
return result
}
func main() {
var acc int64
var i int64 = 1
maxRoutines := runtime.NumCPU()
c := make(chan struct{}, maxRoutines)
for i := 0; i < maxRoutines; i++ {
c <- struct{}{}
}
for true {
<-c
acc += i
go func(acc int64) {
defer func() { c <- struct{}{} }()
if numberOfDevisor(acc) > 1000 {
fmt.Println(acc)
os.Exit(0)
}
}(acc)
i++
}
}