Benchmarks लिखना
func BenchmarkName(b *testing.B) {
for i := 0; i < b.N; i++ {
// code to measure
}
}
Anatomy of a Benchmark Function
एक benchmark function measured हो रहे code को b.N बार दोहराता है, जहां Go का testing framework एक stable timing measurement पाने के लिए N को अपने आप काफी बड़ा चुनता है -- यहां एक manually looped simulation के रूप में दिखाया गया।
उदाहरण: Anatomy of a Benchmark Function
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// Define the function fibonacci
func fibonacci(n int) int {
// Check whether n < 2
if n < 2 {
// Send n back to the caller
return n
}
// Short declaration: create a, b and infer the type
a, b := 0, 1
// Loop: repeat while the condition holds
for i := 2; i <= n; i++ {
a, b = b, a+b
}
// Send b back to the caller
return b
}
func main() {
const simulatedN = 1000
for i := 0; i < simulatedN; i++ {
fibonacci(20)
}
fmt.Println("ran fibonacci(20) simulatedN times:", simulatedN)
fmt.Println("result:", fibonacci(20))
}
Login to try C/C++/Java/PHP code in the editor
Excluding Setup from Timing
जब किसी benchmark को loop से पहले महंगे setup की ज़रूरत हो (जैसे test data बनाना), उस setup के ठीक बाद b.ResetTimer() call करना इसे measured time से बाहर रखता है, ताकि सिर्फ test किए जा रहे code का असल में समय लिया जाए।
उदाहरण: Excluding Setup from Timing
package main
import "fmt"
func sumSlice(nums []int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
// setup (would be excluded from timing via b.ResetTimer() in a real benchmark)
data := make([]int, 1000)
for i := range data {
data[i] = i
}
// timed portion
result := sumSlice(data)
fmt.Println("sum:", result)
}
Login to try C/C++/Java/PHP code in the editor
Running Benchmarks
'go test -bench=.' किसी package में हर BenchmarkXxx function चलाता है, कितनी iterations चलीं और प्रति operation average time report करते हुए, जो changes में performance compare करने का standard तरीका है।
उदाहरण: Running Benchmarks
go test -bench=.
⚠️ Run this in your own terminal or Node.js environment.
- किसी benchmark function को exact Benchmark prefix के बिना नाम देना, इसलिए 'go test -bench' इसे discover नहीं करेगा।
- benchmark के अंदर test किए जा रहे code को b.N बार loop करना भूल जाना -- Go एक stable measurement पाने के लिए N अपने आप तय करता है।
- timed loop के अंदर एक-बार का setup काम शामिल करना बजाय setup के बाद b.ResetTimer() से timer reset करने के।
- Benchmark functions BenchmarkXxx नाम के होते हैं, एक *testing.B लेते हैं, और _test.go files में रहते हैं।
- Measured किए जा रहे code को b.N तक एक loop में चलना चाहिए, एक count जिसे Go का testing framework अपने आप adjust करता है।
- 'go test -bench=.' benchmarks चलाता है और operations per second और प्रति operation time report करता है।
- b.ResetTimer() किसी benchmark के timed हिस्से से setup काम को बाहर रखता है।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: