dongxing4643 2014-10-03 21:36
浏览 5
已采纳

创建一个rand结构

I found the following in this codebase, someone commented on this method with a TODO like so

    // TODO avoid using rand.Float64 method. it uses a singleton lock and may cause
    // performance issues. Instead, instantiate a rand struct and use that to call
    // Float64()

    func standardStrategy(l *ledger) bool {
        return rand.Float64() <= probabilitySend(l.Accounting.Value())
    }

func probabilitySend(ratio float64) float64 {
    x := 1 + math.Exp(6-3*ratio)
    y := 1 / x
    return 1 - y
}

What does this mean?

  • 写回答

1条回答 默认 最新

  • doutuoji8418 2014-10-03 22:16
    关注

    I think what it means is this: the rand package has something called a Rand struct, which has random generating functions, that probably don't lock a global lock, so probably the writer of the comment meant using this struct. i.e.:

    r := rand.New(rand.NewSource(1234))
    
    fmt.Println(r.Float64())
    

    The function used in this code is global to the package and uses a globally initialized Rand struct, called internally globalRand, which has an internal mutex. So avoiding using it saves this locking.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?