英文:
Go: time.sleep and memory usage
问题
当运行下面的代码时,程序从大约1.5M开始,然后逐渐增长到6.4M。我想知道为什么会这样。移除time.sleep可以解决这个问题。
有没有办法在默认情况下使用for-select模式,并在默认情况下睡眠一段时间而不改变内存?
在睡眠后调用*runtime.GC()*可以解决这个问题。我们能否在不调用GC的情况下实现相同的效果?
package main
import (
"time"
)
func main() {
c := make(chan struct{})
for {
select {
case <-c:
//some work
default:
//some work
time.Sleep(time.Millisecond * 1)
}
}
}
相同的情况也适用于:
package main
import (
"time"
)
func main() {
c := make(chan struct{})
for {
select {
case <-c:
case <-time.After(time.Millisecond * 10):
}
}
}
经过一段时间的研究,我使用以下代码实现了它。仍然想知道为什么time.sleep会增加内存使用量?
package main
import (
"time"
)
func main() {
c := make(chan bool)
timer := time.NewTimer(0)
for {
select {
case <-c:
default:
timer.Reset(time.Millisecond * 1)
<-timer.C
}
}
}
英文:
When running the code below, the program starts at around 1.5M and then gradually grows until 6.4M. I'm wondering why.
Removing time.sleep fixes the issue.
Is there a way to use the for-select pattern with a default and sleep some time in the default without any mem change?
Calling runtime.GC() after the sleep does fix the issue. Can we achieve the same thing without having to call the GC ?
package main
import (
"time"
)
func main() {
c := make(chan struct{})
for {
select {
case <-c:
//some work
default:
//some work
time.Sleep(time.Millisecond * 1)
}
}
}
Same with :
package main
import (
"time"
)
func main() {
c := make(chan struct{})
for {
select {
case <-c:
case <-time.After(time.Millisecond * 10):
}
}
}
After some time researching, I achieved it with the following code. Still wonder why time.sleep increases mem usage?
package main
import (
"time"
)
func main() {
c := make(chan bool)
timer := time.NewTimer(0)
for {
select {
case <-c:
default:
timer.Reset(time.Millisecond * 1)
<-timer.C
}
}
}
答案1
得分: -1
你可以使用select
和<-time.After()
来实现超时:
select {
case res := <-c:
fmt.Println("做一些工作")
case <-time.After(time.Second * 1):
fmt.Println("超时")
}
如果你想了解程序如何利用内存,你可以进行性能分析。这篇文章是关于这个主题的一个很好的参考。
英文:
You can implement a timeout using a select
and receive from <-time.After()
:
select {
case res := <-c:
fmt.Println("do some work")
case <-time.After(time.Second * 1):
fmt.Println("timeout")
}
In case you want to understand how your program is utilizing memory you can do profiling. Here is a nice article about this topic.
答案2
得分: -2
经过一段时间的研究,我用以下代码实现了它。
package main
import (
"time"
)
func main() {
c := make(chan bool)
timer := time.NewTimer(0)
for {
select {
case <-c:
default:
timer.Reset(time.Millisecond * 1)
<-timer.C
}
}
}
英文:
After some time researching, I achieved it with the following code.
package main
import (
"time"
)
func main() {
c := make(chan bool)
timer := time.NewTimer(0)
for {
select {
case <-c:
default:
timer.Reset(time.Millisecond * 1)
<-timer.C
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论