英文:
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 "testing"
func BenchmarkEcho1(b *testing.B) {
for i := 0; i < 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 < len(os.Args); i++ {
s += os.Args[i]
}
fmt.Println(s)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论