How to implement Random sleep in golang

huangapple go评论91阅读模式
英文:

How to implement Random sleep in golang

问题

我正在尝试实现随机时间延迟(在Golang中)

r := rand.Intn(10)
time.Sleep(100 * time.Millisecond)  // 正常工作
time.Sleep(time.Duration(r) * time.Microsecond)    // 不工作(类型不匹配 int 和 time.Duration)
英文:

I am trying to implement random time sleep (in Golang)

r := rand.Intn(10)
time.Sleep(100 * time.Millisecond)  //working 
time.Sleep(r * time.Microsecond)    // Not working (mismatched types int and time.Duration)

答案1

得分: 57

匹配time.Sleep的参数类型:

r := rand.Intn(10)
time.Sleep(time.Duration(r) * time.Microsecond)

这段代码之所以有效,是因为time.Duration的底层类型是int64

type Duration int64

文档链接:https://golang.org/pkg/time/#Duration

英文:

Match the types of argument to time.Sleep:

r := rand.Intn(10)
time.Sleep(time.Duration(r) * time.Microsecond)

This works because time.Duration has int64 as its underlying type:

type Duration int64

Docs: https://golang.org/pkg/time/#Duration

答案2

得分: 6

如果你尝试多次运行相同的rand.Intn函数,你会发现输出总是相同的数字。

就像官方文档https://golang.org/pkg/math/rand/中所写的那样:

顶级函数,如Float64和Int,使用一个默认的共享Source,在每次运行程序时产生确定性的值序列。如果需要每次运行时不同的行为,请使用Seed函数初始化默认的Source。

代码应该像这样:

rand.Seed(time.Now().UnixNano())
r := rand.Intn(100)
time.Sleep(time.Duration(r) * time.Millisecond)
英文:

If you try to run same rand.Intn several times, you will see always the same number in output

Just like its written in the official docu https://golang.org/pkg/math/rand/

> Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.

It rather should look like

rand.Seed(time.Now().UnixNano())
r := rand.Intn(100)
time.Sleep(time.Duration(r) * time.Millisecond)

huangapple
  • 本文由 发表于 2017年6月14日 13:21:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/44536045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定