登录
首页 >  Golang >  Go问答

统计一个函数被调用的次数方法?

来源:stackoverflow

时间:2024-03-12 10:54:28 211浏览 收藏

你在学习Golang相关的知识吗?本文《统计一个函数被调用的次数方法?》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我正在开发一个带有调用函数的 api 的 web 服务器。该函数执行繁重的工作并缓存结果。我的设计方式是,如果没有缓存并且多个用户同时使用相同的参数调用此 api,则服务器仅对第一个请求调用该函数一次,而所有其他请求都会等待完成作业,并且从缓存中返回响应。

我用这种方式编写了一个测试:

func testconcurentrequests(t *testing.t) {
    var wg sync.waitgroup
    for i := 0; i < 10; i++ {
        wg.add(1)
        go func() {
            // do the request
            wg.done()
        }
    }
    wg.wait()
}

我可以通过在该繁重函数中打印一个值来检查我的代码是否正常工作,并检查控制台以查看它是否只出现一次,但我正在寻找一种方法来使测试失败(如果该函数已被多次调用)次。像这样的事情:

if n := NumberOfCalls(MyHeavyFunction); n > 1 {
    t.Fatalf("Expected heavy function to run only once but called %d times", n)
}

解决方案


我建议将您的繁重功能分解为缓存部分和实际处理部分。这里的缓存部分将是并发客户端的外观。这里的被测系统实际上是缓存层,决定是否转发请求、保留或从缓存返回。因此,为了测试您需要模拟执行处理的实际函数,并且模拟应该记录它服务了多少个请求。

以下是基于某些假设的演示:

package main

import "fmt"

func CreateCachedProcessor(processor Processing) func(string) string {
    //cache here
    return func(req string) string {
        //Assume you have some logic to call the actual processor based on your conditions
        return processor.ProcessRequest(req)
    }
}

type Processing interface {
    ProcessRequest(string) string
}

type HeavyProcessing struct{}

func (p *HeavyProcessing) ProcessRequest(request string) string {
    return "response"
}

type HeavyProcessingRecorder struct {
    Count int
}

func (p *HeavyProcessingRecorder) ProcessRequest(request string) string {
    p.Count += 1
    return "response recorded"
}

func main() {

    //normal
    hp := &HeavyProcessing{}
    c := CreateCachedProcessor(hp)
    fmt.Println(c("req1"))

    //Test with recorder
    hpr := &HeavyProcessingRecorder{}
    cr := CreateCachedProcessor(hpr)
    cr("req1")
    cr("req1")
    cr("req1")
    fmt.Println("No. of times Called ", hpr.Count)

}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《统计一个函数被调用的次数方法?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>