Path: utzoo!utgpu!utstat!jarvis.csri.toronto.edu!mailrus!cornell!uw-beaver!rice!sun-spots-request From: achhabra@uceng.uc.edu (atul k chhabra) Newsgroups: comp.sys.sun Subject: Fortran 300 times faster than C for computing cosine (on Sun3 & 4) Keywords: Software Message-ID: <764@uceng.UC.EDU> Date: 21 Mar 89 11:24:44 GMT Sender: usenet@rice.edu Organization: Univ. of Cincinnati, College of Engg. Lines: 67 Approved: Sun-Spots@rice.edu Original-Date: 7 Mar 89 23:12:30 GMT X-Sun-Spots-Digest: Volume 7, Issue 203, message 7 of 14 I chanced upon a segment of code that runs approximately 300 times faster in FORTRAN than in C. I have tried the code on Sun3(OS3.5) and on Sun4(OS4.0) (of course, on Sun4 the -f68881 flag was not used.) The results are similar on both machines. Can anyone enlighten me on this bizzare result? Listing of cosc.c: __________ /* * Compile using: * cc -f68881 -O -o cosc cosc.c -lm. */ #include main() { int i; float tmp; for(i=0;i<262144;i++) tmp=cos(2.5)*cos(2.5)*cos(2.5)*cos(2.5); } Listing of cosf.f __________ c c Compile using: c f77 -f68881 -O -o cosf cosf.f c program cosf integer i real tmp do 10 i=1,262144 tmp=cos(2.5)*cos(2.5)*cos(2.5)*cos(2.5) 10 continue end Timings on Sun3(OS3.5): % time cosc 55.6u 1.0s 1:49 51% 24+8k 12+1io 0pf+0w ^^^^^ % time cosf 0.2u 0.0s 0:00 75% 16+8k 4+0io 0pf+0w ^^^^ [[ This is a good one! You've gotten tricked by one of the most common optimization snares around. For f77, "-O" defaults to "-O3", which includes global optimization. Presumably it also does dead code elimination. But what constitutes dead code? Well, code that performs calculations that aren't used. How do you define a value that has been used? Ultimately, if it has an effect on the outside world, or more specifically, if it or something it effects is written or printed. Your cosf.f does neither; "tmp" is never used for anything important, so your entire program gets optimized away! Add "print *,tmp" after the body of the loop and cosf.f takes alot longer. Interestingly enough, it still appears to be quicker than cosc.c. --wnl ]] Atul Chhabra, Dept. of Electrical & Computer Engineering, ML 030, University of Cincinnati, Cincinnati, OH 45221-0030. voice: (513)556-4766 INTERNET: achhabra@ucesp1.ece.uc.edu [129.137.33.114] OR achhabra@uceng.uc.edu [129.137.33.1]