malloc和tcmalloc比较

文章对比了标准库函数malloc和free与Google的tcmalloc在多线程环境中进行大量内存分配和释放的效率。结果显示,tcmalloc由于其优化的内存管理和内部缓存机制,在相同条件下比malloc显著提高了性能,减少了总耗时。

两个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函数

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值