TCMalloc 优化 Nginx 的性能

TCMalloc(Thread-Caching Malloc)与标准glibc库的malloc实现一样的功能,但是TCMalloc在效率和速度效率都比标准malloc高很多。TCMalloc是google-perftools工具中的一个(gperftools四个工具分别是:TCMalloc、heap-checker、heap-profiler和cpu-profiler),这个工具是开源的,以源码形式发布。如果觉得自己维护一个内存分配器麻烦的话,可以考虑将TCMalloc静态库连接到你的程序中。使用的时候和glibc中的malloc调用方式一模一样。你需要做的只是把TCMalloc的动态库或者静态库连接进你的程序中,你就可以获得一个高效,快速,安全的内存分配器。

当追求nginx极致性能的时候会发现会发现linux默认使用的glibc库内存分配的能力并不高,这个时候可以考了tcmalloc,tcmalloc分配内存的效率会高出很多。

与标准的glibc库的malloc相比,TCMalloc在内存的分配效率和速度要高,可以在高并发的情况下很好的控制内存的使用,提高服务器的性能,降低负载。

tcmalloc


 

下载相关软件包


官方下载地址:

https://github.com/gperftools/gperftools/releases/download/gperftools-2.7/gperftools-2.7.tar.gz

https://download-mirror.savannah.gnu.org/releases/libunwind/libunwind-1.2.tar.gz

本地下载地址:

http://down.whsir.com/downloads/gperftools-2.7.tar.gz

http://down.whsir.com/downloads/libunwind-1.2.tar.gz

cd /usr/local/src/
wget http://nginx.org/download/nginx-1.14.0.tar.gz
wget http://down.whsir.com/downloads/gperftools-2.7.tar.gz
wget http://down.whsir.com/downloads/libunwind-1.2.tar.gz

安装所需依赖


cd /usr/local/src/
wget http://nginx.org/download/nginx-1.14.0.tar.gz
wget http://down.whsir.com/downloads/gperftools-2.7.tar.gz
wget http://down.whsir.com/downloads/libunwind-1.2.tar.gz

​

解压编译安装libunwind和gperftools


安装libunwind库:如果系统是64位的需要先安装libunwind库,32位系统则不需要安装。

libunwind库为基于64位CPU和操作系统的程序提供了基本的堆栈辗转开解功能,其中包括用于输出堆栈跟踪的API用于以编程方式辗转开解堆栈的API以及支持C++异常处理机制的API。

tar zxf libunwind-1.2.tar.gz
cd libunwind-1.2
CFLAGS=-fPIC ./configure
make CFLAGS=-fPIC
make CFLAGS=-fPIC install
cd ..

gperftools的安装64位:

tar zxf gperftools-2.7.tar.gz
cd gperftools-2.7
./configure
make
make install
echo "/usr/local/lib" >> /etc/ld.so.conf
ldconfig

可以加入参数只编译tcmalloc(./configure --enable-minimal、--disable-cpu-profiler、--disable-heap-profiler、--disable-heap-checker、--disable-debugalloc),64位操作系统不安装libunwind也不会报错,注意生成的库文件是libtcmalloc_minimal.*
64位操作系统,如下

./configure 

32位系统,不需要安装libunwind,但是一定要添加–enable-frame-pointers参数,如下

./configure --enable-frame-pointers 
make && make install

编译进nginx


编译时要添加--with-google_perftools_module参数,我这里使用的全新nginx编译,如果已有编译好的nginx,只需要执行前面第二步后单独添加一个--with-google_perftools_module参数重新编译即可

为gperftools创建一个线程目录

mkdir /tmp/tcmallocchmod 777 /tmp/tcmalloc/

配置nginx.conf,在#pid logs/nginx.pid;下面增加一行

google_perftools_profiles /tmp/tcmalloc;

最后启动nginx并验证

[root@localhost nginx-1.16.1]# /usr/local/nginx/sbin/nginx -s reload
[root@localhost nginx-1.16.1]# lsof -n | grep -i tcmalloc
nginx     48921       nobody   12w      REG              253,0         0   17582842 /tmp/tcmalloc.48921

猜你喜欢

转载自blog.csdn.net/qq_34556414/article/details/106959700