- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我编写了以下代码作为 Cython 中并行计算的一个简单示例。在我的示例中,我创建了两个工作对象并让它们并行运行。我想概括此实现以使用可变数量的 worker 。问题是我找不到存储 Worker 对象数组并使用 nogil 访问它们的方法。有办法吗?显然,我可以使用下面的技术(最多达到一些合理的硬编码数量的 worker )一起破解一些合理的东西,但如果存在的话,我想要一些更优雅和可维护的东西。
这是代码。关键部分在 if use_parallel 下:
# distutils: language = c
# cython: cdivision = True
# cython: boundscheck = False
# cython: wraparound = False
# cython: profile = False
cimport numpy as cnp
import numpy as np
from cython.parallel import parallel, prange
from libc.math cimport sin
cimport openmp
cnp.import_array()
ctypedef cnp.float64_t FLOAT_t
ctypedef cnp.intp_t INT_t
ctypedef cnp.ulong_t INDEX_t
ctypedef cnp.uint8_t BOOL_t
cdef class Parent:
cdef cnp.ndarray numbers
cdef unsigned int i
cdef Worker worker1
cdef Worker worker2
def __init__(Parent self, list numbers):
self.numbers = <cnp.ndarray[FLOAT_t, ndim=1]> np.array(numbers,dtype=float)
self.worker1 = Worker()
self.worker2 = Worker()
cpdef run(Parent self, bint use_parallel):
cdef unsigned int i
cdef float best
cdef int num_threads
cdef cnp.ndarray[FLOAT_t, ndim=1] numbers = <cnp.ndarray[FLOAT_t, ndim=1]> self.numbers
cdef FLOAT_t[:] buffer1 = self.numbers[:(len(numbers)//2)]
buffer_size1 = buffer1.shape[0]
cdef FLOAT_t[:] buffer2 = self.numbers[(len(numbers)//2):]
buffer_size2 = buffer2.shape[0]
# Run the workers
if use_parallel:
print 'parallel'
with nogil:
for i in prange(2, num_threads=2):
if i == 0:
self.worker1.run(buffer1, buffer_size1)
elif i == 1:
self.worker2.run(buffer2, buffer_size2)
else:
print 'serial'
self.worker1.run(buffer1, buffer_size1)
self.worker2.run(buffer2, buffer_size2)
#Make sure they both ran
print self.worker1.output, self.worker2.output
# Choose the worker that had the best solution
best = min(self.worker1.output, self.worker2.output)
return best
cdef class Worker:
cdef public float output
def __init__(Worker self):
self.output = 0.0
cdef void run(Worker self, FLOAT_t[:] numbers, unsigned int buffer_size) nogil:
cdef unsigned int i
cdef unsigned int j
cdef unsigned int n = buffer_size
cdef FLOAT_t best
cdef bint first = True
cdef FLOAT_t value
for i in range(n):
for j in range(n):
value = sin(numbers[i]*numbers[j])
if first or (value < best):
best = value
first = False
self.output = best
我的测试脚本是这样的:
from parallel import Parent
import time
data = list(range(20000))
parent = Parent(data)
t0 = time.time()
output = parent.run(False)
t1 = time.time()
print 'Serial Result: %f' % output
print 'Serial Time: %f' % (t1-t0)
t0 = time.time()
output = parent.run(True)
t1 = time.time()
print 'Parallel Result: %f' % output
print 'Parallel Time: %f' % (t1-t0)
它产生这个输出:
serial
-1.0 -1.0
Serial Result: -1.000000
Serial Time: 6.428081
parallel
-1.0 -1.0
Parallel Result: -1.000000
Parallel Time: 4.006907
最后,这是我的 setup.py:
from distutils.core import setup
from distutils.extension import Extension
import sys
import numpy
#Determine whether to use Cython
if '--cythonize' in sys.argv:
cythonize_switch = True
del sys.argv[sys.argv.index('--cythonize')]
else:
cythonize_switch = False
#Find all includes
numpy_include = numpy.get_include()
#Set up the ext_modules for Cython or not, depending
if cythonize_switch:
from Cython.Distutils import build_ext
from Cython.Build import cythonize
ext_modules = cythonize([Extension("parallel.parallel", ["parallel/parallel.pyx"],include_dirs = [numpy_include],
extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'])])
else:
ext_modules = [Extension("parallel.parallel", ["parallel/parallel.c"],include_dirs = [numpy_include],
extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'])]
#Create a dictionary of arguments for setup
setup_args = {'name':'parallel-test',
'version':'0.1.0',
'author':'Jason Rudy',
'author_email':'jcrudy@gmail.com',
'packages':['parallel',],
'license':'LICENSE.txt',
'description':'Let\'s try some parallel programming in Cython',
'long_description':open('README.md','r').read(),
'py_modules' : [],
'ext_modules' : ext_modules,
'classifiers' : ['Development Status :: 3 - Alpha'],
'requires':[]}
#Add the build_ext command only if cythonizing
if cythonize_switch:
setup_args['cmdclass'] = {'build_ext': build_ext}
#Finally
setup(**setup_args)
必须用gcc编译,mac上可以用
export CC=gcc
在运行 setup.py 之前。
最佳答案
据我所知,nogil
不支持 Python 对象的索引(以及强制转换,...)。因此,在将 Workers
存储在内置 Python list
中时,我们会收到以下消息:
cdef list workers
workers = [Worker(), Worker(), Worker(), Worker()]
留言:
Indexing Python object not allowed without gil
您可以尝试这样的操作 (经过测试,似乎工作正常):
此处的解决方法是对 nogil
部分中要使用的所有内容使用 C 语法:
cdef PyObject ** workers
cdef int * buf_sizes
cdef FLOAT_t ** buffers
并使用来自 libc.stdlib
的旧式 malloc
分配这些数组。
代码:
# distutils: language = c
# cython: cdivision = True
# cython: boundscheck = False
# cython: wraparound = False
# cython: profile = False
cimport numpy as cnp
import numpy as np
from cython.parallel import parallel, prange
from libc.math cimport sin
cimport openmp
cnp.import_array()
ctypedef cnp.float64_t FLOAT_t
ctypedef cnp.intp_t INT_t
ctypedef cnp.ulong_t INDEX_t
ctypedef cnp.uint8_t BOOL_t
# Pyobject is the C representation of a Python object
# This allows casts in both ways...
cimport cython
from cpython cimport PyObject
# C memory alloc features
from libc.stdlib cimport malloc, free
cdef FLOAT_t MAXfloat64 = np.float64(np.inf)
cdef class Parent:
cdef cnp.ndarray numbers
cdef unsigned int i
cdef PyObject ** workers
cdef int nb_workers
cdef int * buf_sizes
cdef FLOAT_t ** buffers
def __init__(Parent self, list numbers, int n_workers):
self.numbers = <cnp.ndarray[FLOAT_t, ndim=1]> np.array(numbers,dtype=float)
# Define number of workers
self.nb_workers = n_workers
self.workers = <PyObject **>malloc(self.nb_workers*cython.sizeof(cython.pointer(PyObject)))
# Populate pool
cdef int i
cdef PyObject py_obj
cdef object py_workers
py_workers = [] # For correct ref count
for i in xrange(self.nb_workers):
py_workers.append(Worker())
self.workers[i] = <PyObject*>py_workers[i]
self.init_buffers()
cdef init_buffers(Parent self):
cdef int i, j
cdef int num_threads
cdef int pos, pos_end
cdef int buf_size
num_threads = self.nb_workers
buf_size = len(self.numbers) // num_threads
# Init buffers
self.buffers = <FLOAT_t **>malloc(self.nb_workers * cython.sizeof(cython.pointer(FLOAT_t)))
self.buf_sizes = <int *>malloc(self.nb_workers * cython.sizeof(int))
pos = 0
buf_size = len(self.numbers) // num_threads
for i in xrange(self.nb_workers):
# If we are treating the last worker do everything left
if (i == self.nb_workers-1):
buf_size = len(self.numbers) - pos
self.buf_sizes[i] = buf_size
pos_end = pos + buf_size
self.buffers[i] = <FLOAT_t *>malloc(buf_size * cython.sizeof(FLOAT_t))
for j in xrange(pos, pos_end):
self.buffers[i][j-pos] = <FLOAT_t>self.numbers[j]
pos = pos + buf_size
cpdef run(Parent self, bint use_parallel):
cdef int i
cdef FLOAT_t best
# Run the workers
if use_parallel:
print 'parallel'
with nogil:
for i in prange(self.nb_workers, num_threads=self.nb_workers):
# Changed "FLOAT_t[:]" python object to C array "FLOAT_t *"
(<Worker>self.workers[i]).run(<FLOAT_t *>self.buffers[i], self.buf_sizes[i])
else:
print 'serial'
for i in xrange(self.nb_workers):
(<Worker>self.workers[i]).run(<FLOAT_t *>self.buffers[i], self.buf_sizes[i])
# Make sure they ran
for i in xrange(self.nb_workers):
print (<Worker>self.workers[i]).output
# Choose the worker that had the best solution
best = MAXfloat64
for i in xrange(self.nb_workers):
if ((<Worker>self.workers[i]).output < best):
best = (<Worker>self.workers[i]).output
return best
cdef class Worker:
cdef public float output
def __init__(Worker self):
self.output = 0.0
# Changed "FLOAT_t[:]" python object to C dyn array "FLOAT_t *"
cdef void run(Worker self, FLOAT_t * numbers, unsigned int buffer_size) nogil:
cdef unsigned int i, j
cdef unsigned int n = buffer_size
cdef FLOAT_t best
cdef bint first = True
cdef FLOAT_t value
# Added initialization
best = MAXfloat64
for i in range(n):
for j in range(n):
value = sin(numbers[i]*numbers[j])
if first or (value < best):
best = value
first = False
self.output = best
测试:
from parallel import Parent
import time
data = list(range(20000))
parent = Parent(data, 7)
t0 = time.time()
output = parent.run(False)
t1 = time.time()
print 'Serial Result: %f' % output
print 'Serial Time: %f' % (t1-t0)
t0 = time.time()
output = parent.run(True)
t1 = time.time()
print 'Parallel Result: %f' % output
print 'Parallel Time: %f' % (t1-t0)
输出:
serial
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
Serial Result: -1.000000
Serial Time: 2.741364
parallel
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
Parallel Result: -1.000000
Parallel Time: 0.536419
希望这符合您的要求,或者至少提供了一些想法...请分享您的最终实现...
关于python - Cython 并行计算中可变数量的 worker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19783238/
有没有办法同时运行 2 个不同的代码块。我一直在研究 R 中的并行包,它们似乎都基于在循环中运行相同的函数。我正在寻找一种同时运行不同函数的方法(循环的 1 次迭代)。例如,我想在某个数据对象上创建一
无论如何增加 Parallel.For 启动后的循环次数?示例如下: var start = 0; var end = 5; Parallel.For(start, end, i => { C
我是 Golang 的新手,正在尝试了解并发和并行。我阅读了下面提到的关于并发和并行的文章。我执行了相同的程序。但没有得到相同的(混合字母和字符)输出。首先获取所有字母,然后获取字符。似乎并发不工作,
我正在寻找同时迭代 R 中两个或多个字符向量/列表的方法,例如。有没有办法做这样的事情: foo <- c('a','c','d') bar <- c('aa','cc','dd') for(i in
我对 Raku 很陌生,我对函数式方法有疑问,尤其是 reduce。 我最初有这样的方法: sub standardab{ my $mittel = mittel(@_); my $foo =
我最近花了很多时间来学习实时音频处理的细节,我发现的大多数库/工具都是c / c++代码或脚本/图形语言的形式,并在其中编译了c / c++代码。引擎盖。 使用基于回调的API,与GUI或App中的其
我正在使用 JMeter 进行图像负载测试。我有一个图像名称数组并遍历该数组,我通过 HTTP 请求获取所有图像。 -> loop_over_image - for loop controller
我整个晚上都在困惑这个问题...... makeflags = ['--prefix=/usr','--libdir=/usr/lib'] rootdir='/tmp/project' ps = se
我正在尝试提高计算图像平均值的方法的性能。 为此,我使用了两个 For 语句来迭代所有图像,因此我尝试使用一个 Parallel For 来改进它,但结果并不相同。 我做错了吗?或者是什么导致了差异?
假设您有一个并行 for 循环实现,例如ConcRT parallel_for,将所有工作放在一个 for 循环体内总是最好的吗? 举个例子: for(size_t i = 0; i < size()
我想并行运行一部分代码。目前我正在使用 Parallel.For 如何让10、20或40个线程同时运行 我当前的代码是: Parallel.For(1, total, (ii) =>
我使用 PAY API 进行了 PayPal 自适应并行支付,其中无论用户(买家)购买什么,都假设用户购买了总计 100 美元的商品。在我的自适应并行支付中,有 2 个接收方:Receiver1 和
我正在考虑让玩家加入游戏的高效算法。由于会有大量玩家,因此算法应该是异步的(即可扩展到集群中任意数量的机器)。有细节:想象有一个无向图(每个节点都是一个玩家)。玩家之间的每条边意味着玩家可以参加同一场
我有一个全局变量 volatile i = 0; 和两个线程。每个都执行以下操作: i++; System.out.print(i); 我收到以下组合。 12、21 和 22。 我理解为什么我没有得到
我有以下称为 pgain 的方法,它调用我试图并行化的方法 dist: /***************************************************************
我有一个 ruby 脚本读取一个巨大的表(约 2000 万行),进行一些处理并将其提供给 Solr 用于索引目的。这一直是我们流程中的一大瓶颈。我打算在这里加快速度,我想实现某种并行性。我对 Ru
我正在研究 Golang 并遇到一个问题,我已经研究了几天,我似乎无法理解 go routines 的概念以及它们的使用方式。 基本上我是在尝试生成数百万条随机记录。我有生成随机数据的函数,并将创建一
我希望 for 循环使用 go 例程并行。我尝试使用 channel ,但没有用。我的主要问题是,我想在继续之前等待所有迭代完成。这就是为什么在它不起作用之前简单地编写 go 的原因。我尝试使用 ch
我正在使用 import Control.Concurrent.ParallelIO.Global main = parallel_ (map processI [1..(sdNumber runPa
我正在尝试通过 makePSOCKcluster 连接到另一台计算机: library(parallel) cl ... doTryCatch -> recvData -> makeSOCKm
我是一名优秀的程序员,十分优秀!