Sleep causes a tenfold difference in time interval

73 views
Skip to first unread message

尚义龙

unread,
Nov 4, 2021, 12:19:44 PM11/4/21
to golang-nuts
I was doing pressure testing in my project and found a large gap in the time interval due to time.Sleep, which I abstracted to the following code:
code 1:
```go
func TestSleep(t *testing.T) {
for i := 0; i < 8; i++ {
//time.Sleep(time.Second)
t1 := time.Now()
fmt.Println( time.Since(t1))
}
}
```
output:
```shell
229ns
37ns
36ns
37ns
36ns
38ns
37ns
39ns
```
code 2(add time.Sleep):
```
func TestSleep(t *testing.T) {
for i := 0; i < 8; i++ {
time.Sleep(time.Second)
t1 := time.Now()
fmt.Println( time.Since(t1))
}
}
```
```shell
471ns
267ns
855ns
484ns
359ns
296ns
324ns
302ns
```
I have two questions:
1. Why is there such a big difference between the two results (only the time.Sleep difference)?
2. Why is the first output in code1 much larger than the next?
please.

Robert Engels

unread,
Nov 4, 2021, 12:46:59 PM11/4/21
to 尚义龙, golang-nuts
Because when you sleep you deschedule the process/thread by the OS - and so the cached code and data needs to be reloaded so operations aren’t slower until then. 

On Nov 4, 2021, at 11:19 AM, 尚义龙 <sylh...@gmail.com> wrote:


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/3908bb81-d57f-414b-b514-40016b549789n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages