55. Go - Benchmarking
Benchmarking benchmarks codes to measure its performance. Time to complete.
Same format and setup as testing and example testing.
Requires:
- source code
- test code
Source Code: to benchmark
package main
func sayRandom() string {
return "Random"
}
Test Code:
package main
import "testing"
//import "fmt"
/*func TestSayRandom(t *testing.T) {
x := sayRandom()
if x != "Random" {
t.Error("ERROR: Test Failed. Got:", x, "Expected: Random")
}
}*/
/*func ExampleRandom() {
fmt.Println(sayRandom())
// Output: Random
}*/
func BenchmarkSayRandom(b *testing.B) {
for i := 0; i < b.N; i++ {
sayRandom()
}
}
// requires func format, BenchmarkXxx(b *testing.B) {}
// must have for loop, using b.N as the limit
// run test by using,
go test -bench . // to do all benchmarks
OR
go test -bench SayRandom // to do specific benchmark
Benchmark Results = nanoseconds/operation
Comments
Post a Comment