python高性能计算:cython使用openmp并行(示例)

y.pyx

import cython
from cython import parallel
from cython.parallel import prange

cdef int i
cdef int n = 10000
cdef int sum = 0

for i in prange(n, nogil=True):
    sum += i
    while True:
        pass 

print(sum)


编译文件:

y_setup.py

from distutils.core import setup, Extension
from Cython.Build import cythonize
 
 
ext_modules = [
    Extension(
        "y",
        ["y.pyx"],
        extra_compile_args=['-fopenmp'],
        extra_link_args=['-fopenmp'],
    )
]
 
 
setup(
  name = 'y v1',
  ext_modules = cythonize(ext_modules, 
                          #compiler_directives={'language_level' : "3"}
                          # or "2" or "3str"
                          ),
)


编译:

python y_setup.py build_ext --inplace



运行:

image


image



posted on 2024-07-30 20:24  Angry_Panda  阅读(29)  评论(0编辑  收藏  举报

导航