tcmalloc
tcmalloc은 특정 상황에서 더 유리한 선택일 수 있으며 다음과 같은 상황에서 사용되기 좋습니다:
- 멀티스레드 환경:
- tcmalloc은 멀티스레드 환경에서 효율적으로 동작하도록 최적화되어 있습니다. 스레드 간 메모리 관리와 캐싱을 통해 성능을 향상시킵니다. 따라서 멀티스레드 애플리케이션에서 사용하기 좋습니다.
- 대규모 및 분산 시스템:
- 대규모 분산 시스템, 클라우드 환경 또는 대용량 서버 애플리케이션과 같은 대규모 애플리케이션에서 tcmalloc은 효과적으로 메모리 할당 및 해제를 관리할 수 있어 유용합니다.
- 성능 최적화:
- tcmalloc은 일반적으로 glibc malloc과 비교하여 더 빠른 메모리 할당 및 해제 성능을 제공합니다. 따라서 성능이 중요한 응용 프로그램에서 사용하면 이점을 얻을 수 있습니다.
- 메모리 누수 검사:
- tcmalloc은 메모리 누수 디버깅 및 프로파일링을 위한 도구와 함수를 제공합니다. 메모리 누수를 탐지하고 디버그할 때 유용합니다.
- 메모리 프로파일링:
- tcmalloc은 메모리 할당 및 사용에 대한 통계 및 프로파일링 정보를 수집하는 기능을 제공합니다. 이를 통해 메모리 사용 패턴을 분석하고 최적화할 수 있습니다.
- 사용자 지정 설정 및 튜닝:
- tcmalloc은 다양한 설정 및 튜닝 옵션을 제공하여 애플리케이션에 맞게 조정할 수 있습니다. 이로써 성능 및 메모리 사용을 미세 조정할 수 있습니다.
그러나 모든 상황에서 tcmalloc이 항상 더 나은 선택은 아닙니다. 애플리케이션의 특성과 요구사항, 플랫폼, 그리고 개발자의 경험과 선호도에 따라 다른 메모리 할당 라이브러리나 방법이 더 적합할 수 있습니다. 따라서 tcmalloc을 선택하기 전에 애플리케이션의 요구 사항과 목표를 고려해야 합니다.
Install
Brew install
brew install google-perftools(google performance tools install)
sudo apt-get install libgoogle-perftools-dev(tcmalloc install)
- compile
g++ -std=c++11 -o mal_comparison mal_comparison.cpp
g++ -std=c++11 -o tc_comparison tc_comparison.cpp -ltcmalloc
- comparison 결과
mal_0.0148s
tc_0.0180s
malloc example
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
printf("메모리 할당 실패\\n");
return 1;
}
*ptr = 42;
printf("할당된 값: %d\\n", *ptr);
free(ptr); // 메모리 해제
return 0;
}
할당된 값: 42
tcmalloc example
#include <iostream>
#include <gperftools/malloc_extension.h>
int main() {
// tcmalloc 초기화
MallocExtension::Initialize();
int *ptr = (int *)malloc(10 * sizeof(int));
if (ptr == nullptr) {
std::cout << "메모리 할당 실패" << std::endl;
return 1;
}
// 메모리 사용
// 통계 정보를 저장할 문자열 버퍼 생성
const int buffer_length = 1024; // 적절한 크기로 조정 가능
char buffer[buffer_length];
// tcmalloc 사용 통계 정보 얻기
MallocExtension::instance()->GetStats(buffer, buffer_length);
// 통계 정보 출력
std::cout << "통계 정보:\\n" << buffer << std::endl;
free(ptr);
return 0;
}
MALLOC: 72 ( 0.0 MiB) Bytes in use by application
MALLOC: + 1024000 ( 1.0 MiB) Bytes in page heap freelist MALLOC: + 24496 ( 0.0 MiB) Bytes in central cache freelist MALLOC: + 0 ( 0.0 MiB) Bytes in transfer cache freelist MALLOC: + 8 ( 0.0 MiB) Bytes in thread cache freelists MALLOC: + 2490368 ( 2.4 MiB) Bytes in malloc metadata MALLOC: ------------ MALLOC: = 3538944 ( 3.4 MiB) Actual memory used (physical + swap) MALLOC: + 0 ( 0.0 MiB) Bytes released to OS (aka unmapped) MALLOC: ------------ MALLOC: = 3538944 ( 3.4 MiB) Virtual address space used MALLOC: MALLOC: 6 Spans in use MALLOC: 1 Thread heaps in use MALLOC: 8192 Tcmalloc page size
Call ReleaseFreeMemory() to release freelist memory to the OS (via madvise()). Bytes released to the
malloc(comparison)
#include <iostream>
#include <malloc/malloc.h>
#include <chrono>
int main() {
malloc_statistics_t stats;
malloc_zone_statistics(nullptr, &stats);
std::cout << "메모리 할당 통계 정보:\\n";
std::cout << "할당된 블록 수: " << stats.blocks_in_use << std::endl;
std::cout << "할당된 바이트 수: " << stats.size_in_use << " 바이트" << std::endl;
std::cout << "전체 할당된 바이트 수: " << stats.max_size_in_use << "바이트" << std::endl;
// 시간 측정 시작
auto start = std::chrono::high_resolution_clock::now();
int *ptr = (int *)malloc(10 * sizeof(int));
if (ptr == nullptr) {
std::cout << "malloc: 메모리 할당 실패" << std::endl;
return 1;
}
// 시간 측정 종료
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
// 시간 출력
std::cout << "메모리 할당에 걸린 시간: " << duration.count() << " 초"
<< std::endl;
// 할당한 메모리 사용
free(ptr); // 메모리 해제
return 0;
}
메모리 할당 통계 정보: 할당된 블록 수: 171 할당된 바이트 수: 8560 바이트 전체 할당된 바이트 수: 52800바이트 메모리 할당에 걸린 시간: 5.63e-07 초
tcmalloc(comparison)
#include <iostream>
#include <gperftools/tcmalloc.h>
#include <chrono>
int main() {
// 시간 측정 시작
auto start = std::chrono::high_resolution_clock::now();
int *ptr = (int *)tc_malloc(10 * sizeof(int));
if (ptr == nullptr) {
std::cout << "tc_malloc: 메모리 할당 실패" << std::endl;
return 1;
}
// 시간 측정 종료
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
std::cout << "메모리 할당에 걸린 시간: " << duration.count() << " 초"
<< std::endl;
// 할당 정보 얻기
size_t allocated_bytes = tc_malloc_size(ptr);
std::cout << "할당된 바이트 수: " << allocated_bytes << " 바이트" <<
std::endl;
// 할당한 메모리 사용
tc_free(ptr); // 메모리 해제
return 0;
}
메모리 할당에 걸린 시간: 1.729e-05 초 할당된 바이트 수: 48 바이트
'코딩 > Memory' 카테고리의 다른 글
#6 strategy to allocate/free lots of small objects (0) | 2023.11.03 |
---|---|
#5 Why dynamic allocation of small objects in C++ reserves much more memory than actually needed? (0) | 2023.11.02 |
#4 malloc-lab 동적 할당기 구현 (0) | 2023.10.30 |
#2 mymemory (GitHub) (0) | 2023.10.30 |
#1 메모리 할당의 이해 (0) | 2023.10.30 |