在python2.7中使用OpenMP

2024-09-28 05:18:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是使用OpenMP(速度增加程序和比较结果)。我用scipy.weave来做。 我从矩阵中减去向量乘以数字。我使用python2.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()

但我有一个错误(链接上的图片):

错误

Smth公司。但我不明白到底是什么? 我试过做smth。如下(外接程序代码):

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

但这帮不了我


Tags: intestimportfortimearraymatrixresults

热门问题