Node.JS and Python are interpreted scripting languages. So they have to start the interpreter, compile the Source code and the execute.
In go you have the choice.
go build main.go
./main
So GO programs can be much faster. The problem with measuring the execution time is that you would need a single tasked computer with no other processes running. And there are changes etc… But to get an idea, we use the “time” command (available on MAC and linux).
You should at least call the time two times, several calls give you an better idea but also subsequent calls will be optimized by you operation system, for example the files used will be in read buffers.
time
You can measure any command with time
. It will give you these outputs:
Real time is the actual elapsed time from start to finish. Less is better, but if your CPU is busy doing other things, this number will be higher and is has nothing to do with the program measured.
User time is the portion of CPU time spent within the process in user mode code (outside the kernel). Less is better.
System is the portion of CPU time spent in the kernel within the process. Calling i/o and stuff. Less is better.
On some OS/shell you will get %CPU in addition: % CPU is the percent of cpu time used. Less is better
The Code
package main
import "fmt"
func main() {
fmt.Println("hello")
}
console.log("Hello")
print("Hello")
#!/bin/bash
echo "Node.JS"
time node index.js
time node index.js
echo "Python"
time python3 hello.py
time python3 hello.py
echo "Go run"
time go run main.go
echo "Build Go"
go build -o hello main.go
echo "Execute static binary"
time ./hello
time ./hello
To keep it simple I just did two iterations.
To have an environment without virus scan etc i used an https://www.gitpod.io/
environment
Node.JS
Hello
real 0m0.040s
user 0m0.041s
sys 0m0.001s
Hello
real 0m0.038s
user 0m0.035s
sys 0m0.005s
Node.JS takes about 0.04 seconds.
Python
Hello
real 0m0.085s
user 0m0.054s
sys 0m0.038s
Hello
real 0m0.084s
user 0m0.050s
sys 0m0.040s
Python takes about 0.08 seconds
Go run
hello
real 0m0.470s
user 0m0.213s
sys 0m0.313s
Oh no, go is slow - but this is compilation and execution.
Now we change gears…
Build Go
Execute static binary
hello
real 0m0.002s
user 0m0.003s
sys 0m0.000s
hello
real 0m0.002s
user 0m0.000s
sys 0m0.003s
Go takes 0.002 which multiple times faster than python and Node.JS.
See the full source on github.