How do i write a benchmark script in Go to measure ops/sec

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

How do i write a benchmark script in Go to measure ops/sec

问题

我正在通过编写一个简单的Redis克隆来练习我的Golang。

我该如何编写一个基准测试脚本,以在C并发级别下每秒建立X个连接,处理服务器的协议,并测量每秒执行的操作数?

我可以简单地编写一个实际执行此操作的脚本:

for i := range(1000) {
    // 打开连接
    // 执行命令
    // 关闭连接
}

但我想了解在每秒内如何分配每个并发级别的连接数的概念。

英文:

I am practicing my Golang by writing a simple Redis clone.

How do i write a benchmark script that would establish X connections per second at C concurrency level to deal with my server's protocol and measure how many ops/sec?

I can simply write a script that would actually do this:

for i := range(1000) {
    // Open connection
    // Perform command
    // Close connection
}

But i want to know the concept behind distributing the number of connections per concurrency level per second.

答案1

得分: 7

这个最好通过内置的testing.Benchmark系统来处理。例如,像这样的一个测试用例:

func BenchmarkHello(b *testing.B) {
    for i := 0; i < b.N; i++ {
        fmt.Sprintf("hello")
    }
}

将自动计算出这个函数的时间。有关设置的更多详细信息,请参阅包文档,但如果您之前编写过Go测试用例,那么这应该非常熟悉。

至于并发基准测试的问题,请参阅RunParallel助手,它专门用于帮助处理这个问题。

英文:

This is best handled by the built-in testing.Benchmark system. For example, a test case like:

func BenchmarkHello(b *testing.B) {
    for i := 0; i &lt; b.N; i++ {
        fmt.Sprintf(&quot;hello&quot;)
    }
}

will automatically work out timing calculations for this function. See the package documentation for more details on setting it up, but it should be very familiar if you've written Go test cases before.

To your question about concurrency benchmarking, see the RunParallel helper, which is specifically to assist in this.

huangapple
  • 本文由 发表于 2015年5月13日 06:34:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/30202611.html
匿名

发表评论

匿名网友

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

确定