TCMalloc的全称为Thread-Caching Malloc,是谷歌开发的开源工具google-perftools中的一个成员。与标准的glibc库的Malloc相比,TCMalloc库在内存分配效率和速度上要高很多,这在很大程度上提高了服务器在高并发情况下的性能,从而降低了系统的负载。下面简单介绍如何为Nginx添加TCMalloc库支持。
要安装TCMalloc库,需要安装libunwind(32位操作系统不需要安装)和google-perftools两个软件包,libunwind库为基于64位CPU和操作系统的程序提供了基本函数调用链和函数调用寄存器功能。下面介绍利用TCMalloc优化Nginx的具体操作过程。
1.安装libunwind库
可以从http://download.savannah.gnu.org/releases/libunwind下载相应的libunwind版本,这里下载的是libunwind-0.99-alpha.tar.gz。安装过程如下:
- [root@localhost home]#tar zxvf libunwind-0.99-alpha.tar.gz
- [root@localhost home]# cd libunwind-0.99-alpha/
- [root@localhost libunwind-0.99-alpha]#CFLAGS=-fPIC ./configure
- [root@localhost libunwind-0.99-alpha]#make CFLAGS=-fPIC
- [root@localhost libunwind-0.99-alpha]#make CFLAGS=-fPIC install
2.安装google-perftools
可以从http://google-perftools.googlecode.com下载相应的google-perftools版本,这里下载的是google-perftools-1.8.tar.gz。安装过程如下:
- [root@localhost home]#tar zxvf google-perftools-1.8.tar.gz
- [root@localhost home]#cd google-perftools-1.8/
- [root@localhost google-perftools-1.8]# ./configure
- [root@localhost google-perftools-1.8]#make && make install
- [root@localhost google-perftools-1.8]#echo "/usr/ local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
- [root@localhost google-perftools-1.8]# ldconfig
至此,google-perftools安装完成。
3.重新编译Nginx
为了使Nginx支持google-perftools,需要在安装过程中添加“–with-google_perftools_module”选项重新编译Nginx。安装代码如下:
- [root@localhostnginx-0.7.65]#./configure \
- >--with-google_perftools_module --with-http_stub_status_module --prefix=/opt/nginx
- [root@localhost nginx-0.7.65]#make
- [root@localhost nginx-0.7.65]#make install
到这里Nginx安装完成。
4.为google-perftools添加线程目录
创建一个线程目录,这里将文件放在/tmp/tcmalloc下。操作如下:
- [root@localhost home]#mkdir /tmp/tcmalloc
- [root@localhost home]#chmod 0777 /tmp/tcmalloc
5.修改Nginx主配置文件
修改nginx.conf文件,在pid这行的下面添加如下代码:
广州网站建设,网站建设,广州网页设计,广州网站设计
- #pid logs/nginx.pid;
- google_perftools_profiles /tmp/tcmalloc;
接着,重启Nginx即可完成google-perftools的加载。
6.验证运行状态
为了验证google-perftools已经正常加载,可通过如下命令查看:
广州网站建设,网站建设,广州网页设计,广州网站设计
- [root@ localhost home]# lsof -n | grep tcmalloc
- nginx 2395 nobody 9w REG 8,8 0 1599440 /tmp/tcmalloc.2395
- nginx 2396 nobody 11w REG 8,8 0 1599443 /tmp/tcmalloc.2396
- nginx 2397 nobody 13w REG 8,8 0 1599441 /tmp/tcmalloc.2397
- nginx 2398 nobody 15w REG 8,8 0 1599442 /tmp/tcmalloc.2398
由于在Nginx配置文件中设置worker_processes的值为4,因此开启了4个Nginx线程,每个线程会有一行记录。每个线程文件后面的数字值就是启动的Nginx的pid值。
至此,利用TCMalloc优化Nginx的操作完成。



