我正在尝试使用 pyopenCL 计算 python 中网络摄像头流的平均值。作为一项测试,我正在尝试计算多个帧的代表性矩阵的平均值,如下所示:
import pyopencl as cl
import numpy as np
import time
import os
os.environ['PYOPENCL_CTX']='0'
ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)
length = 480
width = 320
nFrames = 60
matrix = np.zeros(shape=(length,width,nFrames)).astype(np.float32)
for i in range(nFrames):
matrix[:,:,i] = float(i)
matrix_GPU = np.zeros(shape=(length,width)).astype(np.float32)
matrix_CPU = np.zeros_like(matrix_GPU)
final_matrix = np.zeros_like(matrix2t)
matrix_GPU_vector = np.reshape(matrix_GPU,matrix_GPU.size)
mf = cl.mem_flags
dest_buf = cl.Buffer(ctx, mf.WRITE_ONLY, matrix_GPU.nbytes)
prg = cl.Program(ctx, """
__kernel void summatrices(const unsigned int size,
__global float * a,
__global float * b,
__global float * sum)
{
int i = get_global_id(0);
sum[i] = a[i] + b[i];
}
""").build()
t0 = time.time()
for i in range(nFrames):
matrix_GPU = matrix[:,:,i].astype(np.float32)
matrix_GPU_vector = np.reshape(matrix_GPU,matrix_GPU.size)
a_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=matrix_GPU_vector)
b_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=final_matrix)
prg.summatrices(queue, matrix_GPU_vector.shape, None,np.int32(len(matrix_GPU_vector)), a_buf, b_buf, dest_buf)
temp_matrix = np.empty_like(matrix_GPU_vector)
cl.enqueue_copy(queue, temp_matrix , dest_buf)
final_matrix = temp_matrix
final_matrix = final_matrix/nFrames
final_matrix = np.reshape(final_matrix,(length,width))
delta_t = time.time() - t0
print 'OpenCL GPU Multiplication: ' + str(delta_t)
matrix_CPU = np.sum(matrix[:,:,:], axis=2)/nFrames
delta_t = time.time() - (t0 + delta_t)
print 'OpenCL CPU Multiplication: ' + str(delta_t)
#print matrix
#print final_matrix
#print matrix_CPU
eq = (final_matrix==matrix_CPU).all()
print eq
然而,我的代码在我的 GPU 上似乎比在我的 CPU 上慢了 30 倍。这很可能是由于我使用了 for 循环和我缺乏工作组分配。
是否可以去掉 python for-loop 并正确分配我的工作组?