python - 在 Python 2.7 中使用 OpenMP
问题描述
我的任务是使用 OpenMP(加速程序并比较结果)。我scipy.weave
用来做。我从矩阵中减去向量乘以数字。我使用Python 2.7(因为只有这个版本weave
存在)
import weave
import numpy
from numpy import *
from random import *
from time import time
codeOpenMP = \
"""
int i = 0;
omp_set_num_threads(2);
#pragma omp parallel shared(matrix, randRow, c) private(i)
{
#pragma omp for
for(i = 0; i < N*M; i++) {
matrix[0,i] = matrix[0,i] - (c * randRow[i%M]);
}
}
"""
# generate matrix
def randMat(x, y):
randRaw = lambda a: [randint(0, 100) for i in xrange(0, a)]
randConst = lambda x, y: [randRaw(x) for e in xrange(0, y)]
return array(randConst(x, y))
def test():
sizeMat = [100, 1000, 2000, 3000]
results = []
for n in sizeMat:
sourceMat = randMat(n, n)
N, M = sourceMat.shape
randRow = sourceMat[randint(0, N)]
c = randint(0, n)
print "\nTest on size: %dx%d" % (n, n)
""" python test """
matrix = array(sourceMat)
t1 = time()
for i in xrange(N):
matrix[i, :] -= c * randRow
timePython = (time() - t1) * MACRO
print "\tPure python: ", timePython
results.append(matrix)
""" C & OpenMP test """
matrix = array(sourceMat)
t1 = time()
weave.inline(codeOpenMP, ['matrix', 'c', 'randRow', 'N', 'M'],
extra_compile_args=['-O3 fopenmp'],
compiler='gcc', libraries=['gomp'],
headers=['<omp.h>'])
timeOpenMP = (time() - t1) * MACRO
print "\tC plus OpenMP: %s" % (timeOpenMP)
results.append(matrix)
if array_equal(results[0], results[1]) and \
array_equal(results[1], results[2]):
print "\tTest - ok"
else:
print "\tTest - false"
test()
但我有一个错误(链接上的图片):
错误
嗯。有编码,但我不明白到底是什么?我试过做某事。像这样(添加代码):
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
但这对我没有帮助!
解决方案
推荐阅读
- java - 从弹簧工具套件连接到数据库时出错
- sql - SQL 查找从未上课的学生(无子查询或聚合)
- python - 使用 Python 进行日志分析
- javascript - 如何在柏树中获取复制到剪贴板的内容
- recursion - 代码分析忽略 OpenMP 结构;分析单线程代码
- c# - 如何暂停在航点之间移动的 navmesh 代理然后继续?
- r - 有没有办法可以在一个图中绘制 t = 300、350、450 和 500 条线?
- python - 在 matplotlib 中将 y 轴设置为从 0 开始
- typescript - Typescript - const 声明中缺少初始化程序
- pandas - 根据下划线后缀中的数字对熊猫列进行排序