赵占旭的博客

TCMalloc简单测试

测试方式如下:

20个线程同时进行malloc和free的操作,每个线程进行malloc和free的操作1M次,每次申请的大小是操作次数的大小(比如第10次操作,就malloc(10))。
测试每个线程操作1M次malloc和free的时间。

glibc malloc的结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
time use 20118516 second
time use 20159695 second
time use 20209392 second
time use 20243706 second
time use 20314329 second
time use 20409412 second
time use 20497020 second
time use 20485955 second
time use 20536799 second
time use 20530233 second
time use 20615596 second
time use 20697397 second
time use 20783369 second
time use 20798414 second
time use 20832314 second
time use 20844732 second
time use 20847341 second
time use 20877054 second
time use 20919291 second
time use 20924166 second

tcmalloc的结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
time use 6547655 second
time use 6586277 second
time use 6595014 second
time use 6602379 second
time use 6603297 second
time use 6617556 second
time use 6606473 second
time use 6594718 second
time use 6625851 second
time use 6610081 second
time use 6627009 second
time use 6632563 second
time use 6632408 second
time use 6614826 second
time use 6616527 second
time use 6639291 second
time use 6640707 second
time use 6641525 second
time use 6616567 second
time use 6643258 second

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>

#define LOOP_NUM (1024 * 1024)
#define THREAD_NUM 20

static void *fun_thread(void *argv)
{
struct timeval start, end;
gettimeofday(&start, NULL);
uint32_t i;
for(i = 0; i < LOOP_NUM; i++) {
uint8_t *a = malloc(i);
free(a);
}

gettimeofday(&end, NULL);
printf("time use %ld second\n", (end.tv_sec - start.tv_sec) * 1000000 + end.tv_usec - start.tv_usec);
return NULL;
}

void main(void)
{
pthread_t a[THREAD_NUM];
uint8_t i;

for(i = 0; i < THREAD_NUM; i++)
pthread_create(&a[i], NULL, fun_thread, NULL);

for(i = 0; i < THREAD_NUM; i++)
pthread_join(a[i], NULL);
}

编译如下:

1
2
@gcc $< -o $@ -lpthread  
@gcc $< -o $@ -lpthread -ltcmalloc_minimal

注意:所有文章非特别说明皆为原创。为保证信息与源同步,转载时请务必注明文章出处!谢谢合作 :-)

原始链接:http://zhaozhanxu.com/2016/05/06/Linux/2016-05-06-Linux-TCMalloc/

许可协议: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。