运行Go基准测试时出现奇怪的输出。

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

Strange output when running Go Benchmark

问题

我正在尝试为Go语言中的一个简单回声程序编写一个基准函数(来自《Go程序设计语言》一书的练习1.3)。以下是代码:

package echo

import "testing"

func BenchmarkEcho1(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Echo1()
    }
}

当我运行go test -bench=.时,输出如下:

PASS
BenchmarkEcho1-4	-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
[...]
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
 1000000	      1358 ns/op
ok  	gopl.io/ch1/exercise1.3/echo	1.377s

在第一行和最后一行之间有很多-test.bench=Echo1。为什么会出现这种情况?我该如何省略这些行?

英文:

I'm trying to write a benchmark function for a simple echo program in Go (Exercise 1.3 from "The Go Programming Language" book). Here is the code:

package echo

import &quot;testing&quot;

func BenchmarkEcho1(b *testing.B) {
    for i := 0; i &lt; b.N; i++ {
        Echo1()
    }
}

When I run go test -bench=. the output is this:

PASS
BenchmarkEcho1-4	-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
[...]
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
-test.bench=Echo1
 1000000	      1358 ns/op
ok  	gopl.io/ch1/exercise1.3/echo	1.377s

There a lot of -test.bench=Echo1 between the first and the last lines. Why is this happening? What can I do to omit these lines?

答案1

得分: 2

你明白b.N的值非常大,因此Echo1会被执行很多次吗?唯一的解释是Echo1正在打印你看到的文本。

你的Echo1()函数可能包含以下内容:

var s string
for i := 1; i < len(os.Args); i++ {
    s += os.Args[i]
}
fmt.Println(s)
英文:

You understand that b.N has a really big value and thus Echo1 gets executed many many times ?
The only explanation is that Echo1 is printing the text you are seeing.

Your Echo1() function probably contains something like this:

var s string
for i := 1; i &lt; len(os.Args); i++ {
	s += os.Args[i]
}
fmt.Println(s)

huangapple
  • 本文由 发表于 2017年3月29日 08:04:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/43082006.html
匿名

发表评论

匿名网友

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

确定