Golang Tip: Profile Your Code Easily with defer + timeSince()

Listen to this Post

Featured Image
Profiling your Go code is essential for identifying performance bottlenecks. Using `defer` and `time.Since()` is a simple yet effective way to measure function execution time without relying on external tools.

Basic Implementation

package main

import ( 
"fmt" 
"time" 
)

func slowFunction() { 
defer func(start time.Time) { 
fmt.Printf("Execution time: %v\n", time.Since(start)) 
}(time.Now())

// Simulate slow operation 
time.Sleep(2  time.Second) 
}

func main() { 
slowFunction() 
} 

Output:

Execution time: 2.0001234s 

Advanced Use Case: Multiple Defer Timers

func complexWorkflow() { 
start := time.Now() 
defer logTime("complexWorkflow", start)

step1() 
step2() 
}

func step1() { 
start := time.Now() 
defer logTime("step1", start) 
time.Sleep(500  time.Millisecond) 
}

func step2() { 
start := time.Now() 
defer logTime("step2", start) 
time.Sleep(1  time.Second) 
}

func logTime(name string, start time.Time) { 
fmt.Printf("%s took %v\n", name, time.Since(start)) 
} 

You Should Know:

1. Comparing with `pprof`

While `defer + time.Since()` is great for quick checks, Go’s built-in `pprof` provides deeper insights:

go tool pprof -http=:8080 http://localhost:6060/debug/pprof/profile 

2. Logging to a File

For long-running applications, log execution times to a file:

func logToFile(name string, duration time.Duration) { 
f, _ := os.OpenFile("perf.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) 
defer f.Close() 
f.WriteString(fmt.Sprintf("%s: %v\n", name, duration)) 
} 

3. Using `runtime` for Memory Profiling

func printMemUsage() { 
var m runtime.MemStats 
runtime.ReadMemStats(&m) 
fmt.Printf("Alloc = %v MiB", m.Alloc / 1024 / 1024) 
} 

4. Benchmarking with `testing` Package

For automated performance tests:

func BenchmarkFunction(b testing.B) { 
for i := 0; i < b.N; i++ { 
slowFunction() 
} 
} 

Run with:

go test -bench=. -benchmem 

What Undercode Say

Profiling is crucial in production environments. While `defer + time.Since()` is excellent for quick checks, always supplement it with:
– `pprof` for CPU/memory analysis
– Benchmark tests for regression tracking
– Structured logging for long-term monitoring

Linux/Windows Commands for Performance Analysis

  • Linux:
    top -p $(pgrep your_app)  Monitor CPU/Memory 
    strace -c -p PID  System call analysis 
    perf stat ./your_app  Hardware performance counters 
    
  • Windows:
    Get-Process | Where-Object { $_.Name -eq "your_app" } | Select-Object CPU, WS 
    wpr -start CPU -filemode  Windows Performance Recorder 
    

Expected Output:

slowFunction took 2.0001234s 
step1 took 500.456ms 
step2 took 1.000789s 

Prediction

As Go continues evolving, expect tighter integration between lightweight profiling (like defer + time.Since()) and advanced tools like pprof, making performance optimization even more seamless.

References:

Reported By: Branko Pitulic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram