Manage calls to calloc/free through Cython
Project description
Cython Memory Helper
cymem provides two small memory-management helpers for Cython. They make it easy to tie memory to a Python object’s life-cycle, so that the memory is freed when the object is garbage collected.
The most useful is cymem.Pool, which acts as a thin wrapper around the calloc function:
>>> from cymem.cymem cimport Pool >>> cdef Pool mem = Pool() >>> data1 = <int*>mem.alloc(10, sizeof(int)) >>> data2 = <float*>mem.alloc(12, sizeof(float))
The Pool object saves the memory addresses internally, and frees them when the object is garbage collected. Typically you’ll attach the Pool to some cdef’d class. This is particularly handy for deeply nested structs, which have complicated initialization functions. Just pass the pool object into the initializer, and you don’t have to worry about freeing your struct at all — all of the calls to Pool.alloc will be automatically freed when the Pool expires.
Installation
Installation is via pip, and requires Cython.
pip install cymem
Example Use Case: An array of structs
Let’s say we want a sequence of sparse matrices. We need fast access, and a Python list isn’t performing well enough. So, we want a C-array or C++ vector, which means we need the sparse matrix to be a C-level struct — it can’t be a Python class. We can write this easily enough in Cython:
"""Example without Cymem
To use an array of structs, we must carefully walk the data structure when
we deallocate it.
"""
from libc.stdlib cimport calloc, free
cdef struct SparseRow:
size_t length
size_t* indices
double* values
cdef struct SparseMatrix:
size_t length
SparseRow* rows
cdef class MatrixArray:
cdef size_t length
cdef SparseMatrix** matrices
def __cinit__(self, list py_matrices):
self.length = 0
self.matrices = NULL
def __init__(self, list py_matrices):
self.length = len(py_matrices)
self.matrices = <SparseMatrix**>calloc(len(py_matrices), sizeof(SparseMatrix*))
for i, py_matrix in enumerate(py_matrices):
self.matrices[i] = sparse_matrix_init(py_matrix)
def __dealloc__(self):
for i in range(self.length):
sparse_matrix_free(self.matrices[i])
free(self.matrices)
cdef SparseMatrix* sparse_matrix_init(list py_matrix) except NULL:
sm = <SparseMatrix*>calloc(1, sizeof(SparseMatrix))
sm.length = len(py_matrix)
sm.rows = <SparseRow*>calloc(sm.length, sizeof(SparseRow))
cdef size_t i, j
cdef dict py_row
cdef size_t idx
cdef double value
for i, py_row in enumerate(py_matrix):
sm.rows[i].length = len(py_row)
sm.rows[i].indices = <size_t*>calloc(sm.rows[i].length, sizeof(size_t))
sm.rows[i].values = <double*>calloc(sm.rows[i].length, sizeof(double))
for j, (idx, value) in enumerate(py_row.items()):
sm.rows[i].indices[j] = idx
sm.rows[i].values[j] = value
return sm
cdef void* sparse_matrix_free(SparseMatrix* sm) except *:
cdef size_t i
for i in range(sm.length):
free(sm.rows[i].indices)
free(sm.rows[i].values)
free(sm.rows)
free(sm)
We wrap the data structure in a Python ref-counted class at as low a level as we can, given our performance constraints. This allows us to allocate and free the memory in the __cinit__ and __dealloc__ Cython special methods.
However, it’s very easy to make mistakes when writing the __dealloc__ and sparse_matrix_free functions, leading to memory leaks. cymem prevents you from writing these deallocators at all. Instead, you write as follows:
"""Example with Cymem.
Memory allocation is hidden behind the Pool class, which remembers the
addresses it gives out. When the Pool object is garbage collected, all of
its addresses are freed.
We don't need to write MatrixArray.__dealloc__ or sparse_matrix_free,
eliminating a common class of bugs.
"""
from cymem.cymem cimport Pool
cdef struct SparseRow:
size_t length
size_t* indices
double* values
cdef struct SparseMatrix:
size_t length
SparseRow* rows
cdef class MatrixArray:
cdef size_t length
cdef SparseMatrix** matrices
cdef Pool mem
def __cinit__(self, list py_matrices):
self.mem = None
self.length = 0
self.matrices = NULL
def __init__(self, list py_matrices):
self.mem = Pool()
self.length = len(py_matrices)
self.matrices = <SparseMatrix**>self.mem.alloc(self.length, sizeof(SparseMatrix*))
for i, py_matrix in enumerate(py_matrices):
self.matrices[i] = sparse_matrix_init(self.mem, py_matrix)
cdef SparseMatrix* sparse_matrix_init_cymem(Pool mem, list py_matrix) except NULL:
sm = <SparseMatrix*>mem.alloc(1, sizeof(SparseMatrix))
sm.length = len(py_matrix)
sm.rows = <SparseRow*>mem.alloc(sm.length, sizeof(SparseRow))
cdef size_t i, j
cdef dict py_row
cdef size_t idx
cdef double value
for i, py_row in enumerate(py_matrix):
sm.rows[i].length = len(py_row)
sm.rows[i].indices = <size_t*>mem.alloc(sm.rows[i].length, sizeof(size_t))
sm.rows[i].values = <double*>mem.alloc(sm.rows[i].length, sizeof(double))
for j, (idx, value) in enumerate(py_row.items()):
sm.rows[i].indices[j] = idx
sm.rows[i].values[j] = value
return sm
All that the Pool class does is remember the addresses it gives out. When the MatrixArray object is garbage-collected, the Pool object will also be garbage collected, which triggers a call to Pool.__dealloc__. The Pool then frees all of its addresses. This saves you from walking back over your nested data structures to free them, eliminating a common class of errors.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Hashes for cymem-1.31.1-cp35-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0be17b3ee12b4b75bab7d292b6952e0d72cb641db45903f37b5a28153e825541 |
|
MD5 | 9cfa43c678a8ac3fca68f6dcdd1b726b |
|
BLAKE2b-256 | 335af52fdf5f10bceb7482381ce7a299c684c39a62954fc295681b62fb97a91f |
Hashes for cymem-1.31.1-cp35-cp35m-manylinux1_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | f43fe23bfad0f1dda38bd4c3b1ddcf915f0650c84dbc7c4f5145d36109e8e95a |
|
MD5 | 791c99585c96495889d23822009fd099 |
|
BLAKE2b-256 | 4c1ad913d81cfe6f803217a4958d111b26291f76653a0dd5ae240ba58cd924a3 |
Hashes for cymem-1.31.1-cp35-cp35m-macosx_10_6_intel.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 588acb15567a0feb7954f10a0372c38baf77e2860d89262c60c13cbdeabd23d9 |
|
MD5 | 27b4f3f2726aad6abaf27b7bd680b299 |
|
BLAKE2b-256 | 1eea64a740322da1866368629eb0754ee8e0efb821d4f9d737b977f10f42d980 |
Hashes for cymem-1.31.1-cp34-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 13102a1aa5e19f2685029789ba4cca2010bd9417323eabba0b7ea17f41451fd4 |
|
MD5 | 73c1ce007b1b816411017c5ba7a9e95b |
|
BLAKE2b-256 | 115c04696375a9ff54b8d5141e2dd5a048e8bc948791147e2e6ce9bf2ee27e69 |
Hashes for cymem-1.31.1-cp34-cp34m-manylinux1_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 110409a78b0b7e2f8dc858293556c4a071612c30c52d7f97681042d63f495185 |
|
MD5 | 4b228d581cced8324b01ceb23a8b87b4 |
|
BLAKE2b-256 | c2e2e6e590362e114489d21edbe75ec5fab387567bd33d7c005deea1f843d279 |
Hashes for cymem-1.31.1-cp34-cp34m-macosx_10_6_intel.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8dada09070ffacd6fbba0a6c3090062238e57154cc5bf10c2e1a1919268f328a |
|
MD5 | 840512609a5ffcfb18d4595b44c9b69f |
|
BLAKE2b-256 | debaac4592292d958892a412851375f31235af40ae7e2c19dede661a2625ff07 |
Hashes for cymem-1.31.1-cp27-none-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9099fac0039bfa1806c3c9d4fb521c9bb64d59e0e539d1f9337abd72e6fabb89 |
|
MD5 | a35d242702e940e87f4858fba309aac3 |
|
BLAKE2b-256 | 70958c33eb85f50f40406d535e58b7f3bc922dc9fb818a91b401e58a64d07681 |
Hashes for cymem-1.31.1-cp27-cp27mu-manylinux1_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 00121923e4a7b4f6f9abbf119684a1ad72a5be8edd5f098f2a219d2042612edf |
|
MD5 | 5f306b3e19062bb0751935efb1a8b7a4 |
|
BLAKE2b-256 | b233eb2f07f928120c8a4cd9df2845a62ec4cf96eb657eec59d8496304398bce |
Hashes for cymem-1.31.1-cp27-cp27m-macosx_10_6_intel.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | e68bd6fee09345fc556143eb2c78941b78ed7afbd1a6abfe59c2392ffd8fcc02 |
|
MD5 | 610ab1a2277fbd6f058e8498f8bd2381 |
|
BLAKE2b-256 | dd3e951f3dd078371dc66be01bd4abdfcdfea262e8d287b0365cbe62008699cb |