absl::PeriodicSampler — 적응형 샘플링·jitter 회피
#한 줄 요약
absl::profiling_internal::PeriodicSampler는 N번에 한 번 true를 반환하는 atomic 카운터 기반 sampler다. 단순 modulo 분기와 달리 geometric distribution으로 다음 sampling 시점을 결정해 phase-lock과 cache miss bias를 피한다. tcmalloc의 sampling, Abseil의 hashtable instrumentation, gRPC의 trace sampling 등이 모두 이 메커니즘이다.
#동기
샘플링이 필요한 상황은 흔하다.
- 모든 malloc을 추적하지 못한다(비용). N번에 한 번만 stack trace.
- 모든 RPC를 trace하지 못한다. 1% 정도만.
- 모든 hashtable insert에 instrumentation을 걸 수 없다.
가장 단순한 sampler는 counter + modulo다.
// 회피 — 단순하지만 문제 다수std::atomic<uint64_t> counter{0};
bool Sample() { return (counter.fetch_add(1) % 1024) == 0;}문제 세 가지:
- Bias: 호출 빈도가 주기와 공명하면 같은 곳만 sampled. 예를 들어 한 함수가 1024번에 한 번 hot path를 지나면 그 path만 항상 sample.
- Cache contention: counter atomic이 모든 thread의 hot path에 있어 cache line ping-pong.
- Rate 변경 비용: sample rate를 바꾸려면 modulo 분기를 다시 컴파일.
PeriodicSampler가 이 셋을 해결한다.
#API와 사용법
absl/profiling/internal/periodic_sampler.h에 정의.
#include "absl/profiling/internal/periodic_sampler.h"
class MallocSampler : public absl::profiling_internal::PeriodicSampler<MallocSampler, 1024> { public: static int64_t period() { return GetSampleRate(); }};
ABSL_PER_THREAD_TLS_KEYWORD MallocSampler sampler_;
void* Malloc(size_t n) { if (sampler_.Sample()) { RecordStackTrace(n); } return RawMalloc(n);}PeriodicSampler는 CRTP. 템플릿 인자로 default period를 받고 *정적 멤버 period()*로 런타임 변경 가능한 rate를 정의한다.
각 thread의 sampler 인스턴스가 thread-local로 stride를 유지하므로 atomic contention이 사라진다.
#내부 구현
template <typename Tag, int64_t default_period>class PeriodicSampler { public: bool Sample() noexcept { // 빠른 경로 — 99.9% if (ABSL_PREDICT_TRUE(--stride_ > 0)) { return false; } return SubtleConfirmSample(); }
private: bool SubtleConfirmSample() noexcept; void Init();
int64_t stride_ = 0; // thread-local};
template <typename Tag, int64_t default_period>bool PeriodicSampler<Tag, default_period>::SubtleConfirmSample() noexcept { int64_t current_period = Tag::period(); if (current_period <= 0) { stride_ = INT64_MAX; return false; } stride_ = NextStride(current_period); return true;}핵심은 두 가지.
#1. fast path — 단순 decrement
호출 99% 이상이 --stride_ > 0 한 줄이다. branch predictor가 거의 항상 맞춘다. cache line은 thread-local이라 다른 thread와 공유 없음.
#2. NextStride — geometric distribution
int64_t NextStride(int64_t mean_period) { // exponential distribution sample // E[X] = mean_period double u = RandomDouble(); // (0, 1) return static_cast<int64_t>(-std::log(u) * mean_period) + 1;}다음 sampling까지의 간격을 지수 분포에서 뽑는다. 평균은 period지만 실제 간격은 임의. 호출 빈도와 공명하지 않는다 — Poisson process의 성질.
geometric/exponential distribution은 memoryless property를 가진다. “이미 1000회 호출했다”는 사실이 다음 sample까지 남은 횟수에 영향을 주지 않는다. 이게 bias-free의 통계적 보장.
#활용 사례
#tcmalloc — heap profiling
class HeapSampler : public PeriodicSampler<HeapSampler, ...> { public: static int64_t period() { return Static::sample_rate(); }};
void* tc_malloc(size_t size) { void* p = inner_malloc(size); if (size > 0 && sampler_.Sample()) { profiling::RecordAlloc(p, size, CaptureStackTrace()); } return p;}1 MB당 평균 1회 sample 같은 rate. heap profile은 대용량 alloc일수록 높은 확률로 sample되도록 size-weighted geometric을 사용한다.
#Swiss Table — load factor 통계
absl::flat_hash_map은 production에서 random subset의 instance만 통계 수집해 hash quality를 모니터링한다. PeriodicSampler로 1000 인스턴스당 1개를 추적.
#gRPC — trace sampling
grpc_core::Sampler는 같은 메커니즘으로 RPC 1%만 OpenTelemetry trace로 export.
#코드 리뷰 포인트
1. modulo 기반 sampler 발견 → 교체 후보
// 회피if (counter.fetch_add(1) % rate == 0) Sample();
// Goodif (sampler_.Sample()) Sample();counter 기반 sampler는 contention + bias 양쪽 문제가 있다.
2. CRTP Tag::period() 통한 동적 rate
class MySampler : public PeriodicSampler<MySampler, 1024> { public: static int64_t period() { return absl::GetFlag(FLAGS_my_sample_rate); // 런타임 변경 가능 }};flag 하나로 production에서 rate를 조정할 수 있다. 코드 재빌드 불필요.
3. thread-local 보장
// 회피 — atomic stride (contention)class BadSampler { std::atomic<int64_t> stride_; };
// Good — thread-local (PeriodicSampler 기본)ABSL_PER_THREAD_TLS_KEYWORD MySampler sampler_;per-thread instance가 핵심. 잘못 shared singleton으로 만들면 의미가 사라진다.
4. 매우 낮은 rate에서 정확도
geometric distribution은 표본 수가 적으면 분산이 크다. 1만 호출에 1번 sample하면 실제 호출 수와 sample 수의 편차가 클 수 있다. 통계 분석 시 Horvitz-Thompson estimator나 weighted sample을 적용한다.
#std / Folly와의 비교
| 항목 | std | folly::SampledStats | absl::PeriodicSampler |
|---|---|---|---|
| 표준 | × | × | × |
| 분포 | — | uniform | geometric |
| thread-local | — | 일부 | 항상 |
| 동적 rate | — | 가능 | 가능 (CRTP) |
| atomic contention | — | 발생 | 없음 |
folly에는 folly::CoreCachedSharedPtr 등 sampling 도구가 있지만 geometric distribution + thread-local의 조합은 abseil이 가장 정제되어 있다.
#자주 보는 안티패턴
hot path에 RandomDouble() 직접 호출
// 회피 — 매 호출 RNG costif (RandomDouble() < 0.001) Sample();RNG는 비용이 있다. PeriodicSampler는 RNG를 slow path에서만 호출하고 fast path는 단순 decrement.
stride 공유
// 회피 — global stridestatic int64_t shared_stride;if (--shared_stride <= 0) { ... } // race conditionper-thread만이 답.
sample 안에서 sample
if (sampler_.Sample()) { HeavyOperation(); // 그 안에서 또 sampler 호출 → 통계 오염}sampler가 재진입되면 통계가 왜곡된다. sampling block 안에서는 sampler 호출 회피.
#정리
PeriodicSampler는 thread-local + geometric distribution으로 bias-free.- fast path는 단순 decrement, slow path만 RNG 호출.
- CRTP의
Tag::period()로 런타임 rate 변경. - tcmalloc, Swiss Table, gRPC 등의 sampling 기반.
- modulo + atomic 기반 sampler를 발견하면 거의 항상 교체 가치.
#다음 편
Abseil Code Review 시리즈는 여기까지다. Folly 시리즈에서 대응 도구를 비교하거나 EMC++ 시리즈에서 함수 객체·자원 관리의 표준을 더 깊이 본다. Google C++ Style Guide (embedded/standards)에서 사내 코딩 규약과의 연결을 확인할 수 있다.
#관련 항목
- Part 16-02 — CRC32C
- Part 16-01 — Stacktrace / Symbolize
- Part 8-01 — BitGen — RNG 기반
- Part 6-01 — Mutex — 동시성 primitive
- Folly Part 9-03 — sampling — Meta 대응
- Tip of the Week #93: Using absl::Span
Abseil Code Review · 79 of 79
- 1 Abseil Code Review — Google production-grade C++ 라이브러리 분석
- 2 Abseil 개요 — Google이 std를 보완한 이유
- 3 Abseil 설계 철학 — std 호환과 추가 기능의 균형
- 4 Abseil 빌드와 의존성 — Bazel vs CMake
- 5 Abseil LTS vs HEAD 릴리스 모델 분석
- 6 Abseil Versioning과 ABI 호환성 정책
- 7 Abseil 매크로 — ABSL_HAVE_*·ABSL_ATTRIBUTE_*
- 8 Abseil ABSL_PREDICT_TRUE/FALSE — branch hint
- 9 absl::LogSeverity — 로그 레벨 타입
- 10 Abseil type_traits — negation·conjunction·void_t
- 11 Abseil Conformance·Policy 분석
- 12 Abseil Memory utilities 분석
- 13 Abseil raw_logging — heap-free 로깅
- 14 Abseil thread_annotations — clang TSA 통합
- 15 absl::Status — exception-free error handling
- 16 absl::StatusOr<T> — 값 또는 에러
- 17 absl status_macros — ASSIGN_OR_RETURN·RETURN_IF_ERROR
- 18 absl::Status payload — 구조화된 에러 컨텍스트
- 19 absl::Status ↔ exception 변환 패턴
- 20 absl::string_view — non-owning 문자열 참조
- 21 absl::string_view 함정 — dangling·c_str·임시 객체
- 22 absl::StrCat — 가변 인자 문자열 연결과 AlphaNum
- 23 absl::StrSplit — Delimiter·Predicate·컨테이너 변환
- 24 absl::StrJoin — 컨테이너 결합과 Formatter
- 25 absl::StrFormat — type-safe printf·FormatSpec
- 26 Abseil ASCII 함수 — locale-free 분류·대소문자 변환
- 27 Abseil Escape — CEscape·HexEscape·Base64
- 28 absl::flat_hash_map — Swiss Table 기반 hash map
- 29 absl::flat_hash_set — set 버전 Swiss Table
- 30 absl::node_hash_map — stable pointer가 필요할 때
- 31 absl::btree_map — sorted·cache-friendly B-tree
- 32 absl::FixedArray — 런타임 크기 stack 배열
- 33 absl::InlinedVector — small buffer optimization
- 34 Abseil Swiss Table internals — control byte·SIMD probing
- 35 absl::Mutex — reader-writer·fairness·deadlock 검출
- 36 absl::Mutex Conditional Critical Section — Await로 cv 없애기
- 37 absl::Notification — once-only signal
- 38 absl::BlockingCounter·Barrier — 다중 thread 조율
- 39 absl::Mutex annotations — clang thread-safety로 race를 컴파일 타임에
- 40 absl::Time·Duration 분석 — 단단한 type
- 41 absl::Time Format·Parse
- 42 absl::CivilTime 분석
- 43 absl::time_zone 분석
- 44 absl::Time mocking — 테스트 친화 시간
- 45 absl::BitGen — 모던 난수 생성기
- 46 Abseil Random Distributions — Uniform·Exponential
- 47 Abseil Mocking Random — 테스트 결정성
- 48 Abseil Random Seeding·Entropy
- 49 absl::int128·uint128 분석
- 50 absl::bits — popcount·countl_zero
- 51 absl::optional vs std::optional
- 52 absl::variant 분석
- 53 absl::span 분석
- 54 absl::any 분석
- 55 absl::compare — three-way 비교
- 56 Abseil utility — apply·in_place
- 57 Abseil AbslHashValue 분석
- 58 Abseil HashState chaining
- 59 Abseil Custom hashable 구현
- 60 Abseil LOG·VLOG·CHECK 분석
- 61 Abseil LogSink 분석
- 62 Abseil LogEntry·structured logging
- 63 Abseil Stack trace·failure_signal_handler
- 64 ABSL_FLAG 정의 분석
- 65 Abseil ParseCommandLine 동작
- 66 Abseil Flag introspection·validation
- 67 Google 스타일의 Abseil 사용 패턴
- 68 Abseil 자주 보는 anti-pattern
- 69 std → absl 마이그레이션 전략
- 70 absl::Cleanup — 함수 종료 시 실행 보장
- 71 Abseil algorithm container 확장 — c_sort·c_find_if·c_count_if
- 72 absl::function_ref와 any_invocable — 함수 객체 전달의 두 축
- 73 absl::bind_front와 Overload — 함수 객체 보조 도구
- 74 absl::Cord — 분산 시스템용 대용량 문자열
- 75 absl::from_chars·SimpleAtoi — 빠른 숫자 변환
- 76 absl::Cord vs std::string — 선택 기준과 메모리 프로파일
- 77 absl::GetStackTrace와 Symbolize — crash 시 readable stack
- 78 absl::ComputeCrc32c — 하드웨어 가속 체크섬
- 79 absl::PeriodicSampler — 적응형 샘플링·jitter 회피
관련 글
absl::from_chars·SimpleAtoi — 빠른 숫자 변환
absl::SimpleAtoi / SimpleAtof / from_chars — locale-free, exception-free, sscanf 대비 10~50배. std::charconv와의 관계.
같은 시리즈에서 이어 읽기
absl::StrCat — 가변 인자 문자열 연결과 AlphaNum
Part 4-03: absl::StrCat — variadic 문자열 연결, AlphaNum 어댑터, operator+ / ostringstream과의 성능 차이.
같은 시리즈에서 이어 읽기
absl::string_view — non-owning 문자열 참조
Part 4-01: absl::string_view — 복사 없는 문자열 전달, lifetime 책임, std::string_view와의 관계.
같은 시리즈에서 이어 읽기