【问题标题】:How to implement Random sleep in golang如何在golang中实现随机睡眠
【发布时间】:2023-03-10 21:35:01
【问题描述】:

我正在尝试实现随机时间睡眠(在 Golang 中)

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

【问题讨论】:

标签: go random time sleep


【解决方案1】:

将参数类型与time.Sleep匹配:

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

这是因为 time.Durationint64 作为其基础类型:

type Duration int64

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

【讨论】:

  • int64 还是 uint64 ?
  • time.Sleep((rand.Int63n(10)) * time.Second) 我试图传入 int64,但即使这样也行不通。 @DmytroBogatov 可能是正确的。
  • @PrateekBhuwania 试试time.Sleep(time.Duration(rand.Int63n(10))*time.Second)。 Go 中没有自动类型转换。至于我的回答还是正确的:golang.org/pkg/time/#Duration
  • @abhink 是的,您的解决方案是正确的。我只是想知道time.Second是否是int64rand.Int63n()也返回int64,那么为什么在乘法过程中会出现类型不匹配?
【解决方案2】:

如果您尝试多次运行相同的 rand.Intn,您将在输出中看到始终相同的数字

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

顶级函数(例如 Float64 和 Int)使用默认共享源,每次运行程序时都会生成确定的值序列。如果每次运行需要不同的行为,请使用 Seed 函数初始化默认 Source。

它应该看起来像

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

【讨论】:

    猜你喜欢
    • 2016-10-12
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    相关资源
    最近更新 更多