Why is there such a significant difference in the time taken for sending and receiving data through a channel between two goroutines?
golang version 1.18
this is my code
package main
import (
"log"
"time"
)
type Message struct {
msgID int
timeStamp int64
timeTime time.Time
msgType int
}
func main() {
const buffer = 1000
msgChan := make(chan *Message, buffer)
timeSumType1 := time.Time{}
timeSumType2 := time.Time{}
go func() {
for i := 1; i <= 100; i++ {
time.Sleep(time.Millisecond)
timeT1 := time.Now()
msgChan <- &Message{msgID: i, msgType: 1}
timeDiff := time.Now().Sub(timeT1)
log.Println("type 1, id :", i, " <- timeDelta:", timeDiff)
timeSumType1 = timeSumType1.Add(timeDiff)
}
}()
go func() {
for i := 1; i <= 100; i++ {
time.Sleep(100 * time.Millisecond)
timeT1 := time.Now()
msgChan <- &Message{msgID: i, msgType: 2}
timeDiff := time.Now().Sub(timeT1)
log.Println("type 2, id :", i, " <- timeDelta:", timeDiff)
timeSumType2 = timeSumType2.Add(timeDiff)
}
}()
time.Sleep(time.Second * 20)
log.Println("type 1, timeSum:", timeSumType1)
log.Println("type 2, timeSum:", timeSumType2)
}
the second goroutine sleep 100ms,the first goroutine sleep 1ms,
the first goroutine handle the msg type: 1
the second goroutine handle the msg type: 2
this is log :
two goroutine sending channel time cost log
two goroutine total cost time
I think the two goroutine should take almost same time with sending channel;
But Why does the second goroutine take several times longer for sending operations compared to the first goroutine?
What internal factors cause this difference?
cheng xu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.