Skip to content

Instantly share code, notes, and snippets.

What would you like to do? for parallel Cython codes shown in the blog post
# cython: language_level=3
import cython
import numpy as np
from cython.parallel import prange, parallel
from libc.math cimport sqrt
from libc.math cimport nearbyint
@cython.cdivision(True) # used to not checking division, can have 20% performance speed up
def pdist_cy_omp(double [:,:] positions not None, double l):
cdef Py_ssize_t n = positions.shape[0]
cdef Py_ssize_t ndim = positions.shape[1]
pdistances = np.zeros(n * (n-1) // 2, dtype = np.float64)
cdef double [:] pdistances_view = pdistances
cdef double d, dd
cdef Py_ssize_t i, j, k
with nogil, parallel():
for i in prange(n-1, schedule='dynamic'):
for j in range(i+1, n):
dd = 0.0
for k in range(ndim):
d = positions[i,k] - positions[j,k]
d = d - nearbyint(d / l) * l
dd = dd + d * d
pdistances_view[j - 1 + (2 * n - 3 - i) * i // 2] = sqrt(dd)
return pdistances
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
ext_modules = [
extra_compile_args=['-O3', '-ffast-math', '-fopenmp'],
ext_modules = cythonize(ext_modules),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.