TcMalloc的介紹以及Windows下安裝使用


本文由博主(SunboyL)原創,轉載請注明出處:http://www.cnblogs.com/xsln/p/Introduction_TcMalloc.html

需要注意的問題請直接看最后面。

介紹:

  TcMalloc(Thread-CachingMalloc)是google-perftools工具中的一個內存管理庫,與標准的glibc庫中malloc相比,TcMalloc在內存分配的效率和速度上要高很多,可以提升高並發情況下的性能,降低系統的負載。

  TcMalloc比glibc的malloc具有更高的效率。如在主頻為2.84GH的pc上,Glibc的malloc需要使用300ns的時間來執行malloc/free對,而tcmalloc只需要50ns來完成相同的操作(數據來自官方文檔)。

  TcMalloc使用線程內存池的方法,小對象(<=32K)是在內存池中進行分配,使用分配較多的內存空間來優化分配時間,並定時進行垃圾回收操作。而大對象(>32K)則直接在全局控制堆中分配。Tcmalloc可以有效減小多線程間的鎖爭用問題,對於小對象,甚至可以實現0爭用。

 

Windows下安裝使用:

  gperftools可以在VC++ 7.1(Visual Studio 2003)或以后的版本中運行。

  首先在官網下載並解壓gperftools,下載地址為:http://code.google.com/p/gperftools/downloads/list  筆者下載的是:gperftools-2.1.zip

  此壓縮包內含README_windows.txt說明文檔,該文檔包含詳細使用教程。

  打開並編譯gperftools-2.1目錄下的gperftools.sln,編譯完成后會生成多個用於測試的exe文件,你可以手動執行這些文件檢測在你的機子上是否全部通過。  It will also create two binaries, nm-pdb and addr2line-pdb, which you should install in the same directory you install the 'pprof' perl script.(說明文檔中的內容,筆者沒有碰這兩個文件)

  編譯通過后,在Release/Debug目錄下生成libtcmalloc_minimal[-debug].dll和對應的lib文件。使用這兩個文件即可實現對其他工程中malloc/new的替換。

  筆者使用的環境是VS2005,要使用此DLL,你需要添加以下行到工程中:"libtcmalloc_minimal.lib" /INCLUDE:"__tcmalloc",設置如下圖:

 
直觀但不全面的測試:
  
#include <Windows.h> 
#include <iostream>

#define COUNT 1000*1000
void func() { size_t j = 0; for (size_t i = 0; i < COUNT; ++i) { if (j > 1001) { j = 0; } int * pInt = (int*)malloc(i * sizeof(int)); free(pInt); } } void main() { DWORD tStart, tEnd; tStart = timeGetTime(); func(); tEnd = timeGetTime(); printf("%lu\n", tEnd - tStart); }

  對於以上代碼,在不使用tcmalloc(將__tcmalloc標志去掉)時,運行時間需要10000多毫秒(實測14846),而在使用tcmalloc后,運行時間僅需100多毫秒(實測151)。

 
 
留意:
  另外,對於Windows,筆者在gperftools-2.1目錄下的INSTALL文件中發現如下需要留意的文字,如由需要,請自行到INSTALL文件中查找並詳細閱讀:

** Windows (MSVC, Cygwin, and MinGW):

Work on Windows is rather preliminary: we haven't found a good way
to get stack traces in release mode on windows (that is, when FPO
is enabled), so the heap profiling may not be reliable in that
case. Also, heap-checking and CPU profiling do not yet work at
all. But as in other ports, the basic tcmalloc library
functionality, overriding malloc and new and such (and even
windows-specific functions like _aligned_malloc!), is working fine,
at least with VC++ 7.1 (Visual Studio 2003) through VC++ 10.0,
in both debug and release modes. See README.windows for
instructions on how to install on Windows using Visual Studio.

 

 

            http://dirlt.com/tcmalloc.html

 

注意:

需要注意的是最好是自己到http://code.google.com/p/gperftools/ 上下載最新版的gperftools而不是使用下文作者提到的2.1版本。

目前最新版為:

2.1版本可能會對新版vs(如2012)不太兼容。(到上面的官方地址查看gperftools更新日志似乎能得到證實)

雖然筆者曾用簡單程序實測在VS2012環境下gperftools-2.1(對應編譯成2012版本)可以對malloc、free、new、delete進行管理,但是筆者將其使用到大型程序上會出現卡死的情況,原因不明,但在google搜過有網民表示可能是由於delete/delete[]引起的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM