计算函数被调用的次数 [英] Count how many times function was called

查看:284
本文介绍了计算函数被调用的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能在 go

中优雅地使用它。在python中,我可以使用如下属性: / p>

In python I could use attribute like this:

def function():
    function.counter += 1
function.counter = 0

go 有相同的机会吗?

推荐答案

让我引用atomic package文档:
$ b

Let me quote the atomic package documentation:


Package atomic提供了低级原子内存原语,这对于实现同步算法的
很有用。
https://golang.org/pkg/sync/atomic/

相同的代码,但更简单也更安全。

Same code, but simpler and safe too.

package main

import (
    "fmt"
    "sync/atomic"
    "time"
)

var fncCount uint64

func fnc() {
    atomic.AddUint64(&fncCount, 1)
}

func main() {
    for i := 0; i < 42; i++ {
        go fnc()
    }
    // this is bad, because it won't wait for the goroutines finish
    time.Sleep(time.Second)

    fncCountFinal := atomic.LoadUint64(&fncCount)
    fmt.Println(fncCountFinal)
}




$ go run -race main.go

$ go run -race main.go

42

这篇关于计算函数被调用的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆