Skip to content

Instantly share code, notes, and snippets.

@futr
Last active August 29, 2015 13:57
Show Gist options
  • Save futr/9782975 to your computer and use it in GitHub Desktop.
Save futr/9782975 to your computer and use it in GitHub Desktop.
XeonPhi上でOpenMPを使って行列積
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
int main( void )
{
// l * m行列とm * n行列積
int i;
int j;
int k;
int l;
int m;
int n;
double start_time;
double stop_time;
float *matA;
float *matB;
float *matAns;
// 初期設定
l = 10000;
m = 10000;
n = 10000;
// 行列確保
matA = (float *)malloc( sizeof(float) * l * m );
matB = (float *)malloc( sizeof(float) * m * n );
matAns = (float *)malloc( sizeof(float) * l * n );
// 行列の値初期化
for ( i = 0; i < l; i++ ) {
for ( j = 0; j < m; j++ ) {
matA[i * m + j] = (float)rand() / RAND_MAX;
}
}
for ( i = 0; i < m; i++ ) {
for ( j = 0; j < n; j++ ) {
matB[i * n + j] = (float)rand() / RAND_MAX;
}
}
for ( i = 0; i < l; i++ ) {
for ( j = 0; j < n; j++ ) {
matAns[i * n + j] = 0;
}
}
// 時間測定開始
start_time = omp_get_wtime();
// 行列積
// in/outの指定でデバイス側へ/からのコピーを指示する
#pragma offload target( mic ) \
in( matA : length( l * m ) ) \
in( matB : length( m * n ) ) \
inout( matAns : length( l * n ) )
{
#pragma omp parallel for private( j, k ) shared( matA, matB, matAns, l, m, n )
for ( i = 0; i < l; i++ ) {
for ( j = 0; j < n; j++ ) {
for ( k = 0; k < m; k++ ) {
matAns[i * m + j] += matA[i * m + k] * matB[k * n + j];
}
}
}
}
// 終了
stop_time = omp_get_wtime();
// 時間出力
printf( "elapsed %f[sec]\n", stop_time - start_time );
// 出力
/*
puts( "matrix A" );
for ( i = 0; i < l; i++ ) {
for ( j = 0; j < m; j++ ) {
printf( "%3.3e ", matA[i * m + j] );
}
puts( "" );
}
puts( "matrix B" );
for ( i = 0; i < m; i++ ) {
for ( j = 0; j < n; j++ ) {
printf( "%3.3e ", matB[i * n + j] );
}
puts( "" );
}
puts( "matrix Ans" );
for ( i = 0; i < l; i++ ) {
for ( j = 0; j < n; j++ ) {
printf( "%3.3e ", matAns[i * n + j] );
}
puts( "" );
}
*/
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment