- 论坛徽章:
- 2
|
本帖最后由 knull 于 2016-06-21 10:23 编辑
最近在了解内存分配;了解了下jemalloc/tcmalloc——传说中的性能相对glibc内存分配大幅度提高的两个很火的内存分配器。
但是,经过简单的性能测试代码测试,发现性能并没有比glibc好。
难道是我测试方法有问题?请各位大侠赐教,探讨~~~
系统环境:CentOS7.1;512M;1CPU(单核);(VM虚拟机安装)
编译环境:gcc(g++)4.8.5;用的是g++ -g -O2进行编译;
测试环境:单线程,8k次malloc/free。分别测试glibc/tcmalloc/jemallc。对比平均耗时,是us(微妙)级别的。
详细说明:
用内存分配器,一种可以直接调用jemalloc代码;还有一种可以设置环境变量LD_PRELOAD来替换glibc的malloc。
1、我首先测试了直接调用的情况(仅测试了je和glibc):直接调用jemalloc。发现,jemalloc平均耗时至少是glibc的2倍,最高近3倍.
2、设置环境变量,LD_PRELOAD.分别测试了je/tc/glibc。
测试发现,该情况下,je比直接调用耗时减少50%。(这点出乎我的意料,想不通)
je耗时比tc稍好。但是glibc比两者都要稍好(三者都相差不是特别大,不到10%)。
下面附上我的测试代码,请大家帮忙分析下啊~~~- #include <list>
- #include <stdlib.h>
- #include <ctime>
- #include <jemalloc/jemalloc.h>
- #include <string>
- class TimeKeeper
- {
- public :
- TimeKeeper(const char *name,int64_t &count):name_(name),counter_(count)
- {
- clock_gettime(CLOCK_MONOTONIC, &tp_start_);
- }
- ~TimeKeeper()
- {
- struct timespec tp_end;
- clock_gettime(CLOCK_MONOTONIC, &tp_end);
- //
- int64_t cost = tp_end.tv_sec - tp_start_.tv_sec;
- cost = (tp_end.tv_nsec-tp_start_.tv_nsec) + (cost*1000*1000*1000);
- counter_ += cost;
- }
- private :
- struct timespec tp_start_;
- int64_t &counter_;
- std::string name_;
- };
- std::list<void*> buf;
- int32_t loop = 8*1024;
- int32_t MAX_MEM_SIZE = 128*1024;
- int64_t alloc_time_;
- int64_t free_time_;
- int32_t GetRand(int32_t n = 16)
- {
- return rand()%n+1;
- }
- void *myalloc(size_t n)
- {
- TimeKeeper tmp(__FUNCTION__,alloc_time_);
- //return je_malloc(n);
- return malloc(n);
- }
- void myfree(void *ptr)
- {
- TimeKeeper tmp(__FUNCTION__,free_time_);
- //je_free(ptr);
- free(ptr);
- }
- void test_muli_times2()
- {
- int32_t num = GetRand();
- void *ptr = NULL;
- for (int i=0; i< loop; ++i)
- {
- ptr = myalloc(GetRand(MAX_MEM_SIZE));
- --num;
- if (num == 0)
- {
- myfree(ptr);
- num = GetRand();
- }
- else
- {
- buf.push_back(ptr);
- }
- }
- while (!buf.empty())
- {
- ptr = buf.back();
- buf.pop_back();
- myfree(ptr);
- }
- printf("alloc %ld obj! cost %ld'ns! avg = %d!\n",loop,alloc_time_,alloc_time_/loop);
- printf("freed %ld obj! cost %ld'ns! avg = %d!\n",loop,free_time_,free_time_/loop);
- }
- int main ()
- {
- //TYPEPRINT(HashNode);
- test_muli_times2();
- return 0;
- }
复制代码 |
|