顯示具有 cpython 標籤的文章。 顯示所有文章
顯示具有 cpython 標籤的文章。 顯示所有文章

2013年3月20日 星期三

python memory leak

由於 CPython 使用 reference counting 管理記憶體, reference count 到 0 時會立即釋放記憶體, 遇到 memory leak 時, 至少可以用 del 稍微自救一番。

import sys

a = []
print sys.getrefcount(a)  # 2
b = a
print sys.getrefcount(a)  # 3
del b
print sys.getrefcount(a)  # 2

如上所示, 可在程式中用 sys.getrefcount() 檢查 referece count 是否符合預期, 盡量在不用以後立即呼叫 del, 當 reference count 變為 0 時, 會提前釋放記憶體。

注意 python 的 while、for 沒有形成新的 scope, 有可能因此誤判一些物件的生命週期:

for i in range(10):
    pass
print i  # 9, 並非 NameError

備註

附上 CPython 2.7.3 Include/object.h 內關於減 reference 相關的程式:

769 #define Py_DECREF(op)                                   \
770     do {                                                \
771         if (_Py_DEC_REFTOTAL  _Py_REF_DEBUG_COMMA       \
772         --((PyObject*)(op))->ob_refcnt != 0)            \
773             _Py_CHECK_REFCNT(op)                        \
774         else                                            \
775         _Py_Dealloc((PyObject *)(op));                  \
776     } while (0)

可看出在 reference count 為 0 時, 確實會呼叫 deallocator。

今日休閒時間已用盡, 改天再來看看為什麼初始數值為 2。

2011年8月14日 星期日

《CPython 源碼剖析》讀書心得 - ch2 - int

PyIntObject

展開巨集後的定義

typedef struct {
   Py_ssize_t ob_refcnt;
   struct _typeobject *ob_type;
   long ob_ival;
} PyIntObject;

基本操作

這篇記了加法的實作: 加完後檢查溢位,若溢位的話, 改用大數 PyLongObject。

PyInt_AS_LONG vs. PyInt_ASLong

在運算過程中, 視情況會用不同方式取出 ob_ival:

  • 前者是巨集, 沒檢查 type, 速度快
  • 後者是函式, 有檢查 type, 速度慢

其它 type 也會看到類似的操作。

immutable

不可變的物件有許多好處, 包括可以任意被所有程式共享, 不用擔心造成依賴關係, 會不小心互炸。代價是各項操作後, 時常需要產生新的物件, 可能會拖慢速度。若會用到大量物件的話, 通常會搭配 object pool 減少生成物件的次數, 藉此簡省計算時間, 或是進一步在生成前先檢查是否已存在同樣物件, 有的話直接共享同一物件, 不生成重覆的物件。

在後面的例子會看到, CPython 有用 object pool 處理 int, 但也付出無限擴大記憶體的代價; 另外, CPython 只針對小部份範圍的數字共用物件, 以取得效率平衡。

memory management

intobject.c 開頭寫下為了減少 malloc 次數, 而採取的作法, 以及它造成的問題:

/* Integers are quite normal objects, to make object handling uniform.
(Using odd pointers to represent integers would save much space
but require extra checks for this special case throughout the code.)
Since a typical Python program spends much of its time allocating
and deallocating integers, these operations should be very fast.
Therefore we use a dedicated allocation scheme with a much lower
overhead (in space and time) than straight malloc(): a simple
dedicated free list, filled when necessary with memory from malloc().

block_list is a singly-linked list of all PyIntBlocks ever allocated,
linked via their next members. PyIntBlocks are never returned to the system before shutdown (PyInt_Fini).

free_list is a singly-linked list of available PyIntObjects, linked via abuse of their ob_type members.
*/

CPython 配了一塊記憶體自己管 int object 的生成和回收, 這塊記憶體只會愈長愈大, 永遠不會變小, 換句話說, 在 64 bit OS 上, 同時用到五千萬的整數後 (e.g., range(50000000)), 即使之後不會再同時用到五千萬個整數, 還是會占去 8*3*50000000 = 約 1G 不會回收的空間。

PyIntBlocks 和 free_list

#define BLOCK_SIZE  1000    /* 1K less typical malloc overhead */
#define BHEAD_SIZE  8   /* Enough for a 64-bit pointer */
#define N_INTOBJECTS    ((BLOCK_SIZE - BHEAD_SIZE) /
sizeof(PyIntObject))

struct _intblock {
   struct _intblock *next;
   PyIntObject objects[N_INTOBJECTS];
};

typedef struct _intblock PyIntBlock;

static PyIntBlock *block_list = NULL;
static PyIntObject *free_list = NULL;  // the head of next-to-new int object

static PyIntObject *
fill_free_list(void)
{
   PyIntObject *p, *q;
   /* Python's object allocator isn't appropriate for large blocks. */
   p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock));
   if (p == NULL)
       return (PyIntObject *) PyErr_NoMemory();
   ((PyIntBlock *)p)->next = block_list;
   block_list = (PyIntBlock *)p;
   /* Link the int objects together, from rear to front, then return
      the address of the last int object in the block. */
   p = &((PyIntBlock *)p)->objects[0];
   q = p + N_INTOBJECTS;
   while (--q > p)
       q->ob_type = (struct _typeobject *)(q-1);
   q->ob_type = NULL;
   return p + N_INTOBJECTS - 1;
}

這裡用了不少 trick, 若沒先看書, 大概要讀一陣子吧。首先讓 PyIntBlock 不要占超過 1k, 大概是這樣 kernel 比較好找空間, 效率比較高。

fill_free_list 用 ob_type 當作 singly-linked list 的 next, 反正等產生 PyIntObject 時, 就會將它指到正確的值, 開頭的註解有先消毒了, 說會 "abuse of their ob_type members", 好奇 grep 了一下 2.5.2 的程式, 幸好 "abuse" 只出現 29 次 ...。

PyObject *
PyInt_FromLong(long ival)
{
   register PyIntObject *v;
   /*--- Begin of #1 ---*/
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
   if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
       v = small_ints[ival + NSMALLNEGINTS];
       Py_INCREF(v);
       return (PyObject *) v;
   }
#endif
   /*--- End of #1 ---*/
   if (free_list == NULL) {
       if ((free_list = fill_free_list()) == NULL)
           return NULL;
   }
   /* Inline PyObject_New */
   v = free_list;
   free_list = (PyIntObject *)v->ob_type;
   PyObject_INIT(v, &PyInt_Type);
   v->ob_ival = ival;
   return (PyObject *) v;
}

先略過 #1 的部份, 後面再解釋。free_list 指到 linked list 的頭, 準備產生 int object, 在 deallocation 時, 會將 free_list 改指到用不到的 PyIntObject, 所以這塊 int object 的記憶體不會有 memory leak, 只是當 free_list 這串超長, 一堆空間用不到時, 它也不會釋放空間就是了。

small_ints

CPython 初始化時, 會先配置一塊空間存 [-5, 256] 的整數, 改變巨集重編 CPython 可改變這個範圍。

之後用到這範圍整數時, 不會重新產生新的 PyIntObject。上面 #1 那塊程式碼就是從 small_ints 取值, small_ints 也是用 PyIntBlocks 裡的空間。

透過下面的操作說明 small_ints 的效果 (id 會傳回 memroy address):

In [1]: id(-5)
Out[1]: 7747448

In [2]: id(-5)
Out[2]: 7747448  # 沒變, 同一個物件

In [3]: id(-6)
Out[3]: 8558280

In [4]: id(-6)
Out[4]: 8557608  # 變了, 表示這個 -6 是新的物件

In [5]: id(256)
Out[5]: 7753136

In [6]: id(256)
Out[6]: 7753136  # 沒變

In [7]: id(257)
Out[7]: 8557512

In [8]: id(257)
Out[8]: 8557440  # 變了

我原本以為 CPython 像多數語言有共用字串那樣, 有共用所有整數。沒想到只有共用小範圍的整數。仔細想想也有道理, 若每次取數字都要 hash, 效率也會很差吧, 這之間的平衡真難拿捏。

了解 PyIntOjbect 的實作方式後, 才明白為何 CPython 會吃掉這麼多記憶體, 還有為何像 psyco 能在不改 code 的情況下讓 CPython 大幅加速科學計算, 一部份的原因是省下一些生成 PyIntObject 的時間。

2011年7月28日 星期四

《CPython 源碼剖析》讀書心得 - ch1 - python object

固定的記憶體空間

object 初始化後大小不準變動, 這個限制帶來一個好處: 大小不變表示不可能要求更大的記憶體空間; 不要求更大的記憶體空間表示不可能要求重配一塊區域, 因此也不會改變 address, 所以, 不用擔心之後要更改任何 pointer 的值。

這讓我想到 MySQL InnoDB 的設計採用 clustered index 存資料, clustered index 裡的 index columns = primary key (PK) 接著針對其它 index (non-clustered index), MySQL 改存 PK 的值, 而不是存 data table 的 physical location (MyISAM 的作法)。

這個設計帶來兩個影響

  • 優點: data row 改變位置時 (B-Tree 常分割或合併 node), 不用更新 indexes
  • 缺點: indexes (非 PK) 得先找到 PK, 再用 PK 取資料, 多了一步

不過 MySQL 針對缺點又做了 InnoDB cache, 讓常取的資料能一步就取到資料, 但也增加維護成本, 這是另一個議題了。

PyObject

C 裡沒有 OO 的語法, Python 用 #ifdef 來增加選擇性欄位, 用 #define 擴充欄位並保留同樣的 address offset。所有 object 的 struct 開頭都是

typedef struct {
   PyObject_HEAD
   ...
} PyXObject;

PyObject_HEAD 是巨集, 最簡單的定義如下:

#define PyObject_HEAD \\\\
   int ob_refcnt;
   struct _typeobject *ob_type;

另有 PyObject_VAR_HEAD 幫動態的物件加上 ob_size 欄位:

#define PyObject_VAR_HEAD \\\\
   PyObject_HEAD
   int ob_size;

所以, 最基本的 python object 和含有不等量的 object 定義如下:

typedef struct {
   PyObject_HEAD
} PyObject;

typedef struct {
   PyObject_VAR_HEAD
} PyVarObject;

類別 int 的定義如下:

typedef struct {
   PyObject_HEAD
   long ob_ival;
} PyIntObject;

這個作法漂亮的地方在於, 彈性地定義不同類型物件用到的欄位, 又能讓所有物件有共通的開頭欄位。於是, PyObject* 可以指向任何物件, 並能放心地假設:

  • 第一個欄位是 ob_refcnt
  • 第二個欄位是 ob_type

若用 PyVarObvject*, 則能再假設

  • 第三個欄位是 ob_size

以基本型別為例:

intfloatstringlist
ob_refcntob_refcntob_refcntob_refcnt
ob_typeob_typeob_typeob_type
ob_ivalob_fvalob_sizeob_size
ob_shashob_item
......

2011年7月27日 星期三

《CPython 源碼剖析》讀書心得 - ch1 - bytecode

複習一下過年時讀的筆記, 若妄想等我全讀完再整理成文章, 大概這輩子都不會有結果吧。還是讀個一個段落就隨手寫寫, 比較實際。我相當地不熟這個領域, 有錯還請指正。

ch1 開頭只提了一點, 剛好幫我串起了之前的一些記憶。想到其實任何語言都可以自己搞個 VM 和 bytecode,
接著在針對各種硬體實作 VM, 就能跨平台了,
當然, 那些用到硬體相關 函式庫/指令 的程式碼, 就無法跨平台

所以, JVM 之所在在跨平台這點上被特別提及,
主要應該是 JIT 讓 java bytecode 執行得很有效率,
且主要的硬體裝置都有支援, 才會覺得很威。而容易實作 JIT 的原因, 和 bytecode 的設計有很大關聯,
像 JVM 針對 stack machine 不用 register 就省掉不少工
( 但 Anroid 用的 Dalvik 為了快, 又加回使用 register 的設計 )。

而其它語言一開始沒規劃好 bytecode 轉 native code 這段,
後期要補就比較辛苦:

  • 像 Unladen Swallow 想 100% 支援 Python 3 的 CPython,
    得在既有的 python object 上多加其它欄位存 JIT 相關資訊,
    結果是速度有可能變快, 但占用的記憶體空間會變更大
  • PyPy 沒要求 100% 相容 Python, 也沒要求相容 CPython, 做起來省了不少工, 較易發揮
  • JavaScript 的 V8 雖然很威, 也有不少限制, 像是它沒實作 multi-thread, 在瀏覽器端不成問題, 換到平常的應用時, 就會有點綁手綁腳的。《Is node.js best for Comet?提到Plurk 用 node.js 卻因 gc 也在 main process 裡執行, 造成的效率問題。

ps. Unladen Swallow 和 PyPy 是很久以前和 Scott 聊到的, 我沒深入看相關文件, 可能會有誤解。另外, 半年前寫這份筆記後沒多久, 就看到《Unladen Swallow Retrospective》, 科技變遷的太快, 令人不勝唏噓。還沒開始讀相關的文獻, 就聽到它掛掉的消息...。

在 Fedora 下裝 id-utils

Fedora 似乎因為執行檔撞名,而沒有提供 id-utils 的套件 ,但這是使用 gj 的必要套件,只好自己編。從官網抓好 tarball ,解開來編譯 (./configure && make)就是了。 但編譯後會遇到錯誤: ./stdio.h:10...