1. GOMAXPROCS Setting
goimport "runtime" func main() { // Get number of logical CPUs numCPU := runtime.NumCPU() fmt.Printf("Number of CPUs: %d\n", numCPU) // Set GOMAXPROCS (default is NumCPU since Go 1.5) runtime.GOMAXPROCS(numCPU) // Or set via environment variable: // GOMAXPROCS=4 go run main.go }
2. Goroutine Overhead
go// Benchmark: Cost of creating goroutines func BenchmarkGoroutineCreation(b *testing.B) { for i := 0; i < b.N; i++ { var wg sync.WaitGroup wg.Add(1) go func() { wg.Done() }() wg.Wait() } } // Result: ~1-2 microseconds per goroutine
3. When NOT to Use Goroutines
go// ❌ Overkill for simple tasks for _, item := range items { go processItem(item) // Too much overhead for small items } // ✅ Better: Process in batches func processBatch(items []Item) { const batchSize = 100 for i := 0; i < len(items); i += batchSize { end := i + batchSize if end > len(items) { end = len(items) } go processBatchInternal(items[i:end]) } }
4. Profiling Goroutines
goimport ( "net/http" _ "net/http/pprof" "runtime" ) func main() { go func() { http.ListenAndServe("localhost:6060", nil) }() // Check goroutine count fmt.Printf("Number of goroutines: %d\n", runtime.NumGoroutine()) // View in browser: // http://localhost:6060/debug/pprof/goroutine }
Was this helpful?