I am new to golang.
I want to call a function at exactly 1 milliseconds for a certain duration ( 1 second for now ) , the function should be called 1000 time a seconds .
I did follow and implemented multiple approaches using timer and tick , but when testing on a simple function that just increment by one a value every time it's been called I find out that it's only been called about ~630 time in 1 second .
When I call the function in loop and stop it after 1 second , The function is called about ~ 226370427 time in 1 second , which means I have problem with the timer and tick .
Here is my code that I implemented using goroutine concurrency which keeps calling the function that increment every 1 ms using ticker and stopped after 1 second by the main and the sum value is then read using the int channel.
import (
"fmt"
"time"
)
func main() {
tickChan := time.NewTicker(time.Millisecond * 1).C
doneChan := make(chan bool)
resultChan := make(chan int)
go start(tickChan, doneChan, resultChan)
time.Sleep(time.Second * 1)
doneChan <- true // Set it to true to stop the infinte loop in the routine
fmt.Printf("total is : %v
", <-resultChan)
}
func start(tickChan <-chan time.Time, doneChan <-chan bool, resultChan chan int) {
sum := 0 // <-- The the value to increment
for {
select {
case <-tickChan:
sum++
case <-doneChan:
resultChan <- sum
return
}
}
}
I was able to do it in node.js successfully (using nanotimer lib ) and was able to run exactly 1000 in 1 sec for every 1 ms , I was even to do it in microsecond too (tho it was about ~ 988676 in 1 second instead of 1 million )
Edit :
go version go1.10.2 windows/amd64
and go env `
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users
ame\AppData\Local\go-build
set GOEXE=.exe
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOOS=windows
set GOPATH=C:\Users
ame\Documents\Go Projects
set GORACE=
set GOROOT=C:\Go
set GOTMPDIR=
set GOTOOLDIR=C:\Go\pkg\tool\windows_amd64
set GCCGO=gccgo
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=C:\Users
ame\AppData\Local\Temp\go-build403228958=/tmp/go-build -gno-record-gcc-switches
`
EDIT 2 : I tested it on the playground and manged to get 1000 total , I think the issue is with windows .Any way to fix it ?