I saw a Twitter post comparing the speed of a function implemented on Java and Go. (x.com)
The post says:
now the main question is why the Java version is faster than the GO one
Java took 2.1 min and GO took 3.26 min
I wanted to implement it on Crystal just to see how this goes:
def collatz(seed : UInt32)
steps = 0_u32
while seed > 1
while seed%2 == 0
steps += 1
seed /= 2
end
if seed > 1
steps +=1
seed = seed*3 + 1
end
end
return steps
end
seed = 1_u32
start = Time.measure do
while seed != 1_000_000_000
collatzResult = collatz(seed)
if seed%1_000_000 == 0
puts "Seed #{seed} Steps: #{collatzResult}"
end
seed += 1
end
end
puts "collatz took: #{start}"
(Probably not a very good implementation due to my lack of Crystal knowledge)
I compiled it using crystal build --release --no-debug --mcpu native test.cr
and then I ran the binary.
It took 00:08:45.836527390 to complete.
This is way too much execution time and not even close to the time that the Go code (from the twitter post) took on my machine, which was 3m52.714522569s. Not because of this I’m going to stop using Crystal, I’m just wondering why it takes soooo long compared to the Go version.
This is the Go code:
package main
import (
"fmt"
"time"
)
func collatz(seed int) int {
var steps = 0
for seed > 1 {
for seed%2 == 0 {
steps++
seed /= 2
}
if seed > 1 {
steps++
seed = seed*3 + 1
}
}
return steps
}
func main() {
start := time.Now()
for seed := 1; seed <= 1_000_000_000; seed++ {
collatzResult := collatz(seed)
if seed%1_000_000 == 0 {
fmt.Printf("Seed: %d Steps %d\r", seed, collatzResult)
}
}
fmt.Printf("%s took %v\n", "collatz", time.Since(start))
}