0

I have a very basic Fortran question as I am a Fortran beginner. I'm using the following function:

real(8) function matchingformulaStk_c(ij,retwealth,iz,ctr,StockReturnM,stkEshare,stkNshare)

IMPLICIT NONE

integer, INTENT(IN) :: ij,iz,ctr
real(8), intent(in) :: StockReturnM,retwealth,stkEshare,stkNshare
real(8) :: R_existing, R_new
real(8), parameter :: p_vest = 0.95d0, match_level = 0.5d0, R401k = 1.02d0

R_existing = stkEshare*StockReturnM+(1d0-stkEshare)*R401k
R_new =  stkNshare*StockReturnM+(1d0-stkNshare)*R401k

matchingformulaStk_c = R_existing*retwealth + R_new*ygrid(ij,iz)*((1+match_level*p_vest)*tau_grid(ctr))    

end function matchingformulaStk_c

When I profile this function in a larger chunk of code I'm using with Intel VTune, I find that the line R_new = stkNshare*StockReturnM+(1d0-stkNshare)*R401k takes around 20x in CPU time as long as the line R_existing = stkEshare*StockReturnM+(1d0-stkEshare)*R401k.

Is there any obvious reason why this could be the case or is this going to be specific to my application? If there are any resources you could point me to as to figuring out how to speed up code hotspots like this one, that would be much appreciated.

Tim de Silva
  • 314
  • 1
  • 13
  • 3
    I suggest to unlearn `real(8)`, it is ugly code smell. Use named constants. See https://stackoverflow.com/questions/838310/fortran-90-kind-parameter Also, there is no guarantee that kind 8 (provided it exists) is compatible with double precision written using 1d0. Kind 8 constants are written using `1._8`. – Vladimir F Героям слава Jun 03 '22 at 06:26
  • 3
    It's really hard to say anything for sure without a [mre]. In particular, what is `R401k`, and how are you compiling the code? – veryreverie Jun 03 '22 at 08:15
  • Hi @VladimirFГероямслава - thanks for the response! I will definitely make this change. I did not know this! – Tim de Silva Jun 03 '22 at 13:23
  • Hi @veryreverie. Whoops, sorry about not including ``R401k``. I fixed my question to define it. I'm compling the code using the Intel 2019 Fortran complier with the flag ``-Ofast``. – Tim de Silva Jun 03 '22 at 13:25
  • 3
    This may as well be some confusion in the reporting. We would definitely have to see some 1. compilable and testable [mcve], 2. the VTune report you get for such an example. The compiler is doing many reorderings and other optimizations and it may be hard to actually assign sensible times to individual lines of the original Fortran code. – Vladimir F Героям слава Jun 03 '22 at 15:41

0 Answers0