首次运行 Golang 的测试速度较慢。

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

First golang test run is slow

问题

我正在运行一个非常简单的测试,将两个数字相加。

package internal

import "testing"

func TestAddingNumbers(t *testing.T) {
	if add(1, 5) != 6 {
		t.Errorf("Failed Adding numbers")
	}
}

首先,go test -v file.go file_test.go 运行结果为 => ok command-line-arguments 0.434s

而第二次运行
go test -v file.go file_test.go 结果为 => ok command-line-arguments 0.099s

有没有办法让第一次测试更快?
我理解的是,第二次运行更快是因为存在一些缓存。
但在 CI 步骤的上下文中,缓存是不存在的,这会导致速度变慢。

英文:

I'm running a very simple test adding two numbers.

package internal

import "testing"

func TestAddingNumbers(t *testing.T) {
	if add(1, 5) != 6 {
		t.Errorf("Failed Adding numbers")
	}
}

First
go test -v file.go file_test.go runs in => ok command-line-arguments 0.434s

While second in
go test -v file.go file_test.go runs in => ok command-line-arguments 0.099s

Is there a way to make first test faster?
My understanding is that there is some caching happening so the second is faster.
But in the context of CI step, cache won't be there and it will makes things slow.

答案1

得分: 4

你无法让第一个运行更快,因为那是测试实际运行的唯一时间。第二次运行只是使用测试缓存,而不运行测试。

但是,你可以通过禁用测试缓存来使测试运行时间相似。惯用的方法是使用以下标志:

go test -count=1
英文:

You cannot make the first one run faster, because that's the only time the test actually runs. The second run is simply using the test cache, without running the test.

However, you can make the test runs use similar times by disabling the test cache. The idiomatic way to do that is to use the flag:

go test -count=1

huangapple
  • 本文由 发表于 2021年9月19日 03:51:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/69237965.html
匿名

发表评论

匿名网友

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

确定