Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #coding: utf8
- from scipy import weave
- import numpy
- from numpy import *
- from random import *
- from time import time
- # для приятной печати времени
- MACRO = 100
- # C и openMP код
- 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]);
- }
- }
- """
- # C код
- codeC = \
- """
- int i = 0;
- for(i = 0; i < N*M; i++) {
- matrix[0,i] = matrix[0,i] - (c * randRow[i%M]);
- }
- """
- # генерация случайной матрицы x на y
- # элементы матрицы - случайные числа от 0 до 99 включ.
- 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 test """
- matrix = array(sourceMat)
- t1 = time()
- weave.inline(codeC, ['matrix','c', 'randRow','N', 'M'],
- compiler = 'gcc')
- timeOpenMP = (time()-t1)*MACRO
- print "\tPure C: %s"%timeOpenMP
- 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()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement