PHpullh
학습 라이브러리/Go/pprof & 성능 프로파일링

GO · 성능

pprof & 성능 프로파일링

Go 내장 프로파일러로 CPU와 메모리 병목을 찾습니다.

성능고급pprofprofilingbenchmarkCPUmemory

핵심 설명

Go 내장 프로파일러로 CPU와 메모리 병목을 찾습니다.

Go code

// main.go — HTTP 서버에 pprof 연결
package main

import (
	"log"
	"net/http"
	_ "net/http/pprof"   // 이 import만으로 /debug/pprof 활성화
	"runtime/pprof"
	"os"
)

func main() {
	// CPU 프로파일링 (파일로 저장)
	f, err := os.Create("cpu.prof")
	if err != nil { log.Fatal(err) }
	defer f.Close()

	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()

	// 메모리 프로파일링
	defer func() {
		mf, _ := os.Create("mem.prof")
		defer mf.Close()
		pprof.WriteHeapProfile(mf)
	}()

	// 실제 애플리케이션 코드
	heavyWork()

	// HTTP 서버에서 실시간 프로파일링
	go func() {
		log.Println(http.ListenAndServe(":6060", nil))
	}()
	// curl http://localhost:6060/debug/pprof/
}

func heavyWork() {
	s := make([]int, 0)
	for i := 0; i < 1_000_000; i++ {
		s = append(s, i*i)
	}
}

// 분석 명령어:
// go test -cpuprofile=cpu.prof -memprofile=mem.prof -bench=.
// go tool pprof cpu.prof
// go tool pprof -http=:8080 cpu.prof  // 웹 UI
// (pprof) top10
// (pprof) list functionName
// (pprof) web

학습 팁

go test -bench=. -benchmem으로 벤치마크 실행 시 메모리 할당 횟수와 크기도 확인할 수 있습니다.

주의할 점

_ "net/http/pprof" import는 프로덕션에서 활성화하면 보안 위험입니다. 빌드 태그나 환경 변수로 개발/프로덕션을 구분하세요.

자주 묻는 질문

pprof & 성능 프로파일링란 무엇인가요?

Go 내장 프로파일러로 CPU와 메모리 병목을 찾습니다.

pprof & 성능 프로파일링 학습 시 주의할 점은 무엇인가요?

_ "net/http/pprof" import는 프로덕션에서 활성화하면 보안 위험입니다. 빌드 태그나 환경 변수로 개발/프로덕션을 구분하세요.