Performance and Benchmarking Basics
Operation Counts
Performance starts with asking how much work a loop performs as input grows.
operation count
Counting simple operations is deterministic and helps explain performance before measuring real time.
Operation Counts
operation_counts.go
Replay: real traced execution (multi-file project)
package main
import "fmt"
func main() {
var items = 4
visits := 0
total := 0
for i := 1; i <= items; i++ {
visits++
total += i
}
fmt.Println("items=", items)
fmt.Println("visits=", visits)
fmt.Println("total=", total)
fmt.Println("linear=", visits == items)
}
package main
import "fmt"
func main() {
var items = 2
visits := 0
total := 0
for i := 1; i <= items; i++ {
visits++
total += i
}
fmt.Println("items=", items)
fmt.Println("visits=", visits)
fmt.Println("total=", total)
fmt.Println("linear=", visits == items)
}
package main
import "fmt"
func main() {
var items = 6
visits := 0
total := 0
for i := 1; i <= items; i++ {
visits++
total += i
}
fmt.Println("items=", items)
fmt.Println("visits=", visits)
fmt.Println("total=", total)
fmt.Println("linear=", visits == items)
}
items ← 4, visits ← 0, total ← 0
5func main() {6 var items→ 4 = 4 //@items=2, 67 visits→ 0 := 08 total→ 0 := 0visits ← 1, total ← 1
pass 1 of 410for i1 := 1; i <= items4; i++ {11 visits→ 1++12 total→ 1 += i113}All 4 passes — pass 1 is the card above pass ivisitstotal1 1 0 → 1 0 → 1 2 2 1 → 2 1 → 3 3 3 2 → 3 3 → 6 4 4 3 → 4 6 → 10 fmt.Println("items=", items)
15 fmt.Println("items=", items4)16 fmt.Println("visits=", visits4)17 fmt.Println("total=", total10)18 fmt.Println("linear=", visits4 == items4)19}outputitems= 4 visits= 4 total= 10 linear= true
items ← 2, visits ← 0, total ← 0
5func main() {6 var items→ 2 = 27 visits→ 0 := 08 total→ 0 := 0visits ← 1, total ← 1
pass 1 of 210for i1 := 1; i <= items2; i++ {11 visits→ 1++12 total→ 1 += i113}visits ← 2, total ← 3
pass 2 of 210for i2 := 1; i <= items2; i++ {11 visits→ 2++12 total→ 3 += i213}fmt.Println("items=", items)
15 fmt.Println("items=", items2)16 fmt.Println("visits=", visits2)17 fmt.Println("total=", total3)18 fmt.Println("linear=", visits2 == items2)19}outputitems= 2 visits= 2 total= 3 linear= true
items ← 6, visits ← 0, total ← 0
5func main() {6 var items→ 6 = 67 visits→ 0 := 08 total→ 0 := 0visits ← 1, total ← 1
pass 1 of 610for i1 := 1; i <= items6; i++ {11 visits→ 1++12 total→ 1 += i113}All 6 passes — pass 1 is the card above pass ivisitstotal1 1 0 → 1 0 → 1 2 2 1 → 2 1 → 3 3 3 2 → 3 3 → 6 4 4 3 → 4 6 → 10 5 5 4 → 5 10 → 15 6 6 5 → 6 15 → 21 fmt.Println("items=", items)
15 fmt.Println("items=", items6)16 fmt.Println("visits=", visits6)17 fmt.Println("total=", total21)18 fmt.Println("linear=", visits6 == items6)19}outputitems= 6 visits= 6 total= 21 linear= true