I am trying to understand why higher CPU utilization leads to longer latency in reading from channels in golang. Could you help me with this question?
I wrote a test that reads from channels and measure latency between writing to a channel and reading from the channel. It shows that the latency depends on CPU utulization. When one of functions looks like this
func (c *Connection) imitateEncodeAndSend() {
onFinish := time.Now().Add(8 * time.Microsecond)
for time.Now().Before(onFinish) {
runtime.Gosched()
}
}
the average latency of reading from 5 channels is 1,5 microseconds.When runtime.Gosched() is commented the average latency is 10 microseconds. Why latency depends so much on CPU utilization even though there are a lot of CPU available on the host where I test? Could you suggest anything to improve latency when runtime.Gosched() is commented?
I have included the test. It has 156 LOC.
Test with not commented runtime.Gosched() :
$ N=100000 C=5 go run ./multiplex.go
connections: 5, a.iterations: 100000, duration: 1.352864833s, average broadcasting latency: 720ns, average receive latency: 1.504µs, rate: 73917
Test with commented runtime.Gosched():
$ N=100000 C=5 go run ./multiplex.go
connections: 5, a.iterations: 100000, duration: 2.860448459s, average broadcasting latency: 569ns, average receive latency: 10.655µs, rate: 34960