首页 > 解决方案 > 在 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')

但这对我没有帮助!

标签: pythonpython-2.7scipyopenmp

解决方案


推荐阅读