两个demo,分别启动5个线程每轮申请10万次内存,统计时间
//malloc
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#define NUM_THREADS 5
#define NUM_ALLOCATIONS 100000
void *worker(void *arg) {
int i;
struct timeval start, end;
long long elapsed_time_us;
for (i = 0; i < NUM_ALLOCATIONS; i++) {
void *ptr = malloc(1024); // Allocate 1 KiB of memory
free(ptr);
}
return NULL;
}
int main() {
int i;
pthread_t threads[NUM_THREADS];
struct timeval start, end;
long long elapsed_time_us;
gettimeofday(&start, NULL);
for (i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, worker, NULL);
}
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
gettimeofday(&end, NULL);
elapsed_time_us = (end.tv_sec - start.tv_sec) * 1000000LL + (end.tv_usec - start.tv_usec);
printf("Total time for %d allocations: %lld us\n", NUM_THREADS * NUM_ALLOCATIONS, elapsed_time_us);
return 0;
}
执行结果:
Total time for 500000 allocations: 15227 us
//tcmalloc
#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
#include <gperftools/tcmalloc.h>
#define NUM_THREADS 5
#define NUM_ALLOCATIONS 100000
void *worker(void *arg) {
int i;
struct timeval start, end;
long long elapsed_time_us;
for (i = 0; i < NUM_ALLOCATIONS; i++) {
void *ptr = tc_malloc(1024); // Allocate 1 KiB of memory
tc_free(ptr);
}
return NULL;
}
int main() {
int i;
pthread_t threads[NUM_THREADS];
struct timeval start, end;
long long elapsed_time_us;
gettimeofday(&start, NULL);
tc_malloc_size = 256 * 1024 * 1024; // Set the tcmalloc cache size to 256 MiB
for (i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, worker, NULL);
}
for (i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
gettimeofday(&end, NULL);
elapsed_time_us = (end.tv_sec - start.tv_sec) * 1000000LL + (end.tv_usec - start.tv_usec);
printf("Total time for %d allocations: %lld us\n", NUM_THREADS * NUM_ALLOCATIONS, elapsed_time_us);
return 0;
}
执行结果:
Total time for 500000 allocations: 2904 us
总结:
第一个程序使用标准库函数malloc和free来申请和释放内存。在每个线程中,它执行了10万次内存申请和释放操作。由于每次申请的内存大小为1 KiB,因此总共申请了1000 MiB的内存。这些线程并行执行,以最大化利用多核处理器的性能。
第二个程序使用了Google开发的tcmalloc库。与标准的malloc不同,tcmalloc具有更好的性能和可伸缩性。它采用了一种高效的内存管理算法,能够在多线程应用程序中提供快速的内存分配和释放。此外,它还附加了一个内部缓存,用于存储已经申请的内存,可以避免频繁向系统申请内存。在这个程序中,我们也设置了一个256 MiB的缓存,以进一步提高分配和释放内存的速度。通过比较两个程序的运行时间,可以看出tcmalloc的性能确实优于标准的malloc函数