Go Stress test Study Notes:

As always, let’s start with a few things about Gobench:

  • The file name is still xxx_test.go
  • Bench Aaaaaa (BenchAaaaa(b *testing.B)); Bench Aaaaaa (b *testing.B);
  • Function:
  1. Using b.N for polling tests, this is a mandatory option and must be selected.
  2. B. reportallocs (), this is to report specific memory usage. Is optional and optional.

This is the function to test. File name: stress test.go

packagetestfunc GetSum(n int) int {
	var sum = 0
	for i := 1; i<n+1; i++{ sum += i }return sum
}

Copy the code

File name: stress test_test.go

packagetestimport "testing"

func BenchmarkGetSum(b *testing.B) {
	b.ReportAllocs()
	for i:=0; i<b.N; i++{ GetSum(10)}}Copy the code

Here you must use b.N in the for loop.

👇 👇 👇

for i:=0; i<b.N; i++{ GetSum(10)}Copy the code

The use of b.reportallocs () is used to report specific memory usage.

Then there is the stress test method:

Right-click on the tests folder, select Run, and then GoBench.

There will be a wait here…

Here are the results:

Goos: That’s the system you’re testing. In this case, Windows

Goarch: System architecture

Here’s the test data. 7.30ns/OP and 6.92ns /op indicate that each time takes 7.30ns and 6.92ns.

packagetestimport "testing"

func BenchmarkGetSum(b *testing.B) {
	b.Log("BenchmarkGetSum test begins")
	b.ReportAllocs()
	for i:=0; i<b.N; i++{ GetSum(10)}}Copy the code

We can also use b.log(), such as b.log(“BenchmarkGetSum test starts “) to output logs during tests.

The blogger is a student who loves Golang, you can follow the blogger to learn together!

Use of the GO Test [GO Study Notes] | Go Theme month

Juejin. Cn/post / 694319…

[Go] Custom error of exception handling

Juejin. Cn/post / 693915…