【发布时间】:2015-07-10 08:11:05
【问题描述】:
我在至强处理器系统上使用 C 和 FORTRAN 运行 n*n 矩阵乘法代码。我很惊讶地看到这两种方法之间的实时差异。为什么 FORTRAN 代码给了我更快的执行时间?我正在使用dgemm() 并从我的 C 代码中调用了相同的函数。我尝试运行更改循环顺序的通用 C 代码并尝试使用不同的标志来优化模拟过程。我无法达到使用dgemm() 获得的相同响应。
FORTRAN 代码 - dgemm():
#include "stdio.h"
#include "time.h"
#include "sys/time.h"
#include "math.h"
#include "stdlib.h"
long long readTSC(void)
{
/* read the time stamp counter on Intel x86 chips */
union { long long complete; unsigned int part[2]; } ticks;
__asm__ ("rdtsc; mov %%eax,%0;mov %%edx,%1"
: "=mr" (ticks.part[0]),
"=mr" (ticks.part[1])
: /* no inputs */
: "eax", "edx");
return ticks.complete;
}
volatile double gtod(void)
{
static struct timeval tv;
static struct timezone tz;
gettimeofday(&tv,&tz);
return tv.tv_sec + 1.e-6*tv.tv_usec;
}
void dgemm (char *transa, char *transb, int *x, int *xa, int *xb, double *alphaa, double *ma, int *xc, double *mb, int *xd, double *betaa, double *msum, int *xe);
int main(int argc, char** argv)
{
int n = atoi(argv[1]);
long long tm;
//disabling transpose, disabling addition operation in C := alpha*op(A)*op(B) + beta*C
char trans='N';
double alpha=1.0;
double beta=0.0;
long long int p=2*n*n*n;
long double q;
double *a,*b,*sum;
double t_real,t,flop_clk,flops;
int i,j,k;
//memory allocation
a=(double*)malloc(n*n*sizeof(double));
b=(double*)malloc(n*n*sizeof(double));
sum=(double*)malloc(n*n*sizeof(double));
//Matrix Initialization
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
a[i+n*j]=(double)rand();
b[i+n*j]=(double)rand();
sum[i+n*j]=0.0;
}
}
//Clock cycles computation using timing2 function and t_real using timing1 function
t = gtod();
tm = readTSC();
//dgemm function call
dgemm(&trans, &trans, &n, &n, &n, &alpha, a, &n, b, &n, &beta, sum, &n);
tm = readTSC() - tm;
t_real = gtod() - t;
return 0;
}
C 代码 只需取 sum=0 然后
for (i=0;i<n;i++)
{
for (k=0;k<n;k++)
{
for (j=0;j<n;j++)
{
sum [i+n*j] +=a[i+n*k]*b[k+n*j];
}
}
}
编译:
icc –o 用于 C 代码的可执行程序.c
icc -o executable program.c mkl=sequential for the Fortran one
性能
矩阵顺序为 5000*5000,我的代码中得到 4.2 GFLOPS,使用 dgemm() 得到 21.7 GFLOPS。
【问题讨论】:
-
可能有很多原因,但一般来说,Fortran 是为数学工作而设计的,而 Fortran 编译器(开始很好)只是在该语言存在的近 60 年中变得更好。跨度>
-
这样的问题会有很多猜测,但除非您在问题中同时显示 Fortran 和 C 代码,否则没人能给您准确的答案。解释你如何衡量你的基准也是一个好主意。有关传递的工具、编译器和编译器标志的详细信息也会很有用。
-
请显示一些代码所以编辑你的问题。
-
如果 OP 选择修改这个问题以希望重新打开它,我建议 OP 提供数字来显示程序之间的时间差。
-
除了副本中给出的答案之外,列优先与行优先的性质有时会影响缓存性能。
标签: c matrix time fortran matrix-multiplication