performance - Is Fortran easier to optimize than C for heavy calculations? -
from time time read fortran or can faster c heavy calculations. true? must admit hardly know fortran, fortran code have seen far did not show language has features c doesn't have.
if true, please tell me why. please don't tell me languages or libs number crunching, don't intend write app or lib that, i'm curious.
the languages have similar feature-set. performance difference comes fact fortran says aliasing not allowed. code has aliasing not valid fortran programmer , not compiler detect these errors. fortran compilers ignore possible aliasing of memory pointers , allows them generate more efficient code. take @ little example in c:
void transform (float *output, float const * input, float const * matrix, int *n) { int i; (i=0; i<*n; i++) { float x = input[i*2+0]; float y = input[i*2+1]; output[i*2+0] = matrix[0] * x + matrix[1] * y; output[i*2+1] = matrix[2] * x + matrix[3] * y; } }
this function run slower fortran counterpart after optimization. why so? if write values output array may change values of matrix. after pointers overlap , point same chunk of memory (including int
pointer!). c compiler forced reload 4 matrix values memory computations.
in fortran compiler can load matrix values once , store them in registers. can because fortran compiler assumes pointers/arrays not overlap in memory.
fortunately restrict keyword , strict-aliasing have been introduced c99 standard address problem. it's supported in c++ compilers these days well. keyword allows give compiler hint programmer promises pointer not alias other pointer. strict-aliasing means programmer promises pointers of different type never overlap, example double*
not overlap int*
(with specific exception char*
, void*
can overlap anything).
if use them same speed c , fortran. however, ability use restrict keyword performance critical functions means c (and c++) programs safer , easier write. example, consider invalid fortran code: call transform(a(1, 30), a(2, 31), a(3, 32), 30)
, fortran compilers happily compile without warning introduces bug shows on compilers, on hardware , optimization options.
Comments
Post a Comment