nginx性能优化调优之google-perftools

什么是google-perftools?
google-perftools是google公司开发的一款针对 C/C++ 程序的性能分析开源工具,使用该工具可以对 CPU 时间片、内存等系统资源的分配和使用进行分析
google-perftools包含四个工具,分别是:TCMalloc、heap-checker、heap-profiler和cpu-profiler,其中我们本次需要的一个工具TCMalloc是google-perftools的其中一个工具,用于优化内存分配的效率和速度,帮助在高并发的情况下很好的控制内存的使用

运维为什么要使用google-perftools?
使用google开发的google-perftools优化nginx和mysql的内存分配效率和速度,帮助在高并发的情况下控制内存的使用。但是,nginx的内存占用其实是很少的,一个进程占用的内存大概只有12M左右,所以google-perftools对nginx的优化效果可能不太明显

什么是TCMalloc工具?
上面已经说过TCMalloc是google-perftools的一个工具与标准的glibc库的Malloc相比,TCMalloc库在内存分配效率和速度上要高很多,这在很大程序上提高了服务器在高并发情况下的性能,从而降低系统的负载如何为Nginx添加TCMalloc库支持,要安装TCMalloc库,需要安装libunwind和gperftools两个软件包,libunwind库为基于64为CPU操作系统的程序提供了基本函数调用链和函数调用函数寄存器功能,32位操作系统不需要安装。

通过上面的三连问我们已经大致了解google-perftools是什么玩意了,那么下面我们将进行如何安装和使用

安装编译工具:
yum -y install gcc make
yum -y install gcc gcc-c++

安装libunwind:
wget http://download.savannah.gnu.org/releases/libunwind/libunwind-0.99.tar.gz
tar zxvf libunwind-0.99.tar.gz
cd libunwind-0.99/
CFLAGS=-fPIC ./configure --prefix=/usr
make CFLAGS=-fPIC
make CFLAGS=-fPIC install

安装google-perftools:
wget https://github.com/gperftools/gperftools/releases/download/gperftools-2.7/gperftools-2.7.tar.gz
tar zxvf gperftools-2.7.tar.gz
cd gperftools-2.7
./configure --enable-frame-pointers --enable-libunwind --with-tcmalloc-pagesize=32

./configure --enable-frame-pointers
make && make install
注:如果是64位系统,需要先安装libunwind,再在configure gperftools的时候,添加--enable-frame-pointers参数

安装nginx并添加参数
安装nginx省略,如果nginx是在安装google-perftools前已经安装了,那么需要考虑是否平滑升级及平滑重启,平滑升级加入参数即可
例: ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-google_perftools_module

上面虽然已经安装好,但是还是不能够使用,因为没有在nginx配置文件中加入这个模块

1.添加线程目录
mkdir /tmp/tcmalloc
chmod 0777 /tmp/tcmalloc
2.做软连接或引用动态库
echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
/sbin/ldconfig
3.修改nginx.conf配置文件,在pid行添加以下信息,表示开启这个模块
google_perftools_profiles /tmp/tcmalloc;

然后启动或重启nginx

验证即可
nginx 44112 nobody 10w REG 8,4 0 1044489 /tmp/tcmalloc.44112
一个线程会有一个记录文件,由于我只开了一个线程,所以只有一个记录文件

扩展:
启动nginx,发现缺少libprofiler.so.0动态库的支持
/usr/local/nginx/sbin/nginx
/usr/local/nginx/sbin/nginx: error while loading shared libraries: libprofiler.so.0: cannot open shared object file: No such file or directory
这是因为perftools是通过Linux的LD_PRELOAD达到java应用程序运行时,当调用malloc时换用它的libtcmalloc.so
查找系统下是否有libprofiler.so.0动态库
whereis libprofiler.so.0
libprofiler.so: /usr/local/lib/libprofiler.so.0 /usr/local/lib/libprofiler.so
由于不在nginx程序查找的目录下,所以需要创建软链接
评估缺少的动态库支持,可通过ldd /usr/local/nginx/sbin/nginx的方式,查看"not found"部分。
ln -s /usr/local/lib/libprofiler.so.0.4.18 /lib64/libprofiler.so.0

猜你喜欢

转载自blog.51cto.com/jiaxinwang/2465473