25

It is said that Blitz++ provides near-Fortran performance.

Does Fortran actually tend to be faster than regular C++ for equivalent tasks?

What about other HL languages of exceptional runtime performance? I've heard of a few languages suprassing C++ for certain tasks... Objective Caml, Java, D...

I guess GC can make much code faster, because it removes the need for excessive copying around the stack? (assuming the code is not written for performance)

I am asking out of curiosity -- I always assumed C++ is pretty much unbeatable barring expert ASM coding.

foraidt
  • 5,519
  • 5
  • 52
  • 80

16 Answers16

58

Fortran is faster and almost always better than C++ for purely numerical code. There are many reasons why Fortran is faster. It is the oldest compiled language (a lot of knowledge in optimizing compilers). It is still THE language for numerical computations, so many compiler vendors make a living of selling optimized compilers. There are also other, more technical reasons. Fortran (well, at least Fortran77) does not have pointers, and thus, does not have the aliasing problems, which plague the C/C++ languages in that domain. Many high performance libraries are still coded in Fortran, with a long (> 30 years) history. Neither C or C++ have any good array constructs (C is too low level, C++ has as many array libraries as compilers on the planet, which are all incompatible with each other, thus preventing a pool of well tested, fast code).

q-l-p
  • 4,304
  • 3
  • 16
  • 36
David Cournapeau
  • 78,318
  • 8
  • 63
  • 70
  • 1
    Just for the sake of completeness, f90 has pointers, but they are nothing like pointers in C and relatives (thank gott for that). Other than that, you've made some good points. +up – Rook Mar 04 '09 at 14:55
  • Most C & C++ compilers have an option to assume there is no pointer aliasing. That may affect benchmark results. – Ferruccio Mar 04 '09 at 15:03
  • Ferruccio, hmm would this option make this trivial code fail? int f() { int i = 0; int* p = &i; i = 1; return *p; } or am I misunderstanding the aliasing problem? –  Mar 04 '09 at 15:06
  • @Ferrucio: yes, there are options for no pointer aliasing, but they are not standard (unless your C compiler is C99). And that's kind of besides the point: of course, if you are very careful, you can almost always write super fast code in C or C++. But Fortran makes this much easier. – David Cournapeau Mar 04 '09 at 16:14
  • For the pointer aliasing problem, this link is good: http://www.cellperformance.com/mike_acton/2006/05/demystifying_the_restrict_keyw.html – David Cournapeau Mar 04 '09 at 16:15
  • 4
    Why Fortran is *not* faster (within error tolerance) than C++ in all benchmarks from http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=icpp&lang2=ifc&box=1 – jfs Mar 04 '09 at 22:57
  • 5
    I did not say that fortran is faster than C (this assestion does not make sense anyway), I said that fortran is faster and better than C for numerical code, specifically the one relying on arrays: faster and better syntax. The shoutout is a relatively poor benchmark BTW. – David Cournapeau Mar 05 '09 at 03:52
  • 1
    The Fortran source on the shootout page is wretched. Fortran is faster, and more legible, portable, and maintainable than C/C++ for numerics, plain and simple. – user7116 Mar 09 '09 at 04:04
  • 1
    @sixlettervariables: The code shootout page is submitted. If you think the code is wretched, feel free to submit faster code. If you look at the details, Fortran was equivalent to C++ in every task submitted except for k-nucleotide, where there's only one submission and it's terrible. If you can write a fast version for that task, that should fix the comparisons. – Mooing Duck Nov 26 '12 at 21:05
22

Whether fortran is faster than c++ is a matter of discussion. Some say yes, some say no; I won't go into that. It depends on the compiler, the architecture you're running it on, the implementation of the algorithm ... etc.

Where fortran does have a big advantage over C is the time it takes you to implement those algorithms. And that makes it extremely well suited for any kind of numerical computing. I'll state just a few obvious advantages over C:

  • 1-based array indexing (tremendously helpful when implementing larger models, and you don't have to think about it, but just FORmula TRANslate
  • has a power operator (**) (God, whose idea was that a power function will do ? Instead of an operator?!)
  • it has, I'd say the best support for multidimensional arrays of all the languages in the current market (and it doesn't seem that's gonna change so soon) - A(1,2) just like in math
  • not to mention avoiding the loops - A=B*C multiplies the arrays (almost like matlab syntax with compiled speed)
  • it has parallelism features built into the language (check the new standard on this one)
  • very easily connectible with languages like C, python, so you can make your heavy duty calculations in fortran, while .. whatever ... in the language of your choice, if you feel so inclined
  • completely backward compatible (since whole F77 is a subset of F90) so you have whole century of coding at your disposal
  • very very portable (this might not work for some compiler extensions, but in general it works like a charm)
  • problem oriented solving community (since fortran users are usually not cs, but math, phy, engineers ... people with no programming, but rather problem solving experience whose knowledge about your problem can be very helpful)

Can't think of anything else off the top of my head right now, so this will have to do.

Community
  • 1
  • 1
Rook
  • 60,248
  • 49
  • 165
  • 242
  • 12
    1-based array indexing is as much a blessing as a curse. No matter which language I'm stuck using, with whichever convention, it seems like the opposite one is more natural for the problem at hand.... – kquinn Mar 08 '09 at 06:23
  • 10
    yes, 1-based is not better than 0-based. I don't see how it can help for any model - depending on the field, index starts at 0 or 1 (or something else). In signal processing, it is very common to start indexing at 0. – David Cournapeau Mar 09 '09 at 19:04
  • 2
    In "classical" engineering fields (mech, geo, ocean, aero ....) the 1-based indexing is used, no dilemma. Mathematicians also use 1-based. I've also found 1-based more logical, if there is one element length of array=1, if you're on 5th element, =5 ... that sorta thing. – Rook Mar 09 '09 at 20:26
  • 2
    Since all materials (books, articles ... whatever) in those fields are written using that indexing, thinking of the index translation all the time, can be very (extremelly) fatiguing. – Rook Mar 09 '09 at 20:28
  • 1
    C was written to write Unix. Unix was written to do text processing. Neither do an awful lot of exponents so no need for a ** operator, a complex number type or n dimensional arrays. – Martin Beckett May 01 '09 at 03:11
  • @mgb - well, VB certanly wasn't build for numerical calculations, and yet it has a exponentation operator. And besides, I don't care what C was build for. I was adressing a completely different point here. – Rook May 01 '09 at 04:03
  • 10
    C is missing an exponent operator because most CPU's don't have an exponent instruction. It is my understanding that in C, operators are reserved for functions that most hardware will perform in constant time with at most a few instructions. – rpetrich Jul 15 '09 at 17:14
  • The question is about C++, not C. – Pharap Jul 04 '19 at 17:31
  • @Pharap. When talking about operators C and C++ are one and the same. – Garret Gang Feb 28 '20 at 20:59
  • 1
    @GarretGang Not completely. For the order of operations and the semantics on fundamental types they are mostly the same, but C++ also has operator overloading and reference semantics which affect the meaning of certain operators. For example, most assignment operators (e.g. `=`, `+=`) return an lvalue reference, which makes assignment chaining possible. In C, on the other hand, assignment chaining is not possible because there are no reference types. See https://stackoverflow.com/a/22609184. – Pharap Mar 19 '21 at 09:37
  • Fortran has the ability to index array from any integer value to any integer value. While it is very common to start counting with 1, it is also common to start at 0, or even e.g. -42 to 42. It is not an either-or proposition with Fortran. Its default is to start at 1. – Eric Brown Mar 11 '23 at 13:25
9

What Blitz++ is competing against is not so much the Fortran language, but the man-centuries of work going into Fortran math libraries. To some extent the language helps: an older language has had a lot more time to get optimizing compilers (and , let's face it, C++ is one of the most complex languages). On the other hand, high level C++ libraries like Blitz++ and uBLAS allows you to state your intentions more clearly than relatively low-level Fortran code, and allows for whole new classes of compile-time optimizations.

However, using any library effectively all the time requires developers to be well acquainted with the language, the library and the mathematics. You can usually get faster code by improving any one of the three...

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51
7

FORTAN is typically faster than C++ for array processing because of the different ways the languages implement arrays - FORTRAN doesn't allow aliasing of array elements, whereas C++ does. This makes the FORTRAN compilers job easier. Also, FORTRAN has many very mature mathematical libraries which have been worked on for nearly 50 years - C++ has not been around that long!

  • The Fortran EQUIVALENCE statement can create an alias for an array element. – Pete Kirkham Mar 04 '09 at 15:03
  • Yeah, but the compiler then knows about the alias. With C++ (and C) there may be lots of aliases the compiler can't deduce. –  Mar 04 '09 at 21:27
3

the thing with c++ is that it is very close to the hardware level. In fact, you can program at the hardware level (via assembly blocks). In general, c++ compilers do a pretty good job at optimisations (for a huge speed boost, enable "Link Time Code Generation" to allow the inlining of functions between different cpp files), but if you know the hardware and have the know-how, you can write a few functions in assembly that work even faster (though sometimes, you just can't beat the compiler).

You can also implement you're own memory managers (which is something a lot of other high level languages don't allow), thus you can customize them for your specific task (maybe most allocations will be 32 bytes or less, then you can just have a giant list of 32-byte buffers that you can allocate/deallocate in O(1) time). I believe that c++ CAN beat any other language, as long as you fully understand the compiler and the hardware that you are using. The majority of it comes down to what algorithms you use more than anything else.

Grant Peters
  • 7,691
  • 3
  • 45
  • 57
  • 1
    > In fact, you can program at the hardware level (via assembly blocks) And that code is... ASM not C++. Honestly, if you're mangling C++ to look nothing like it was intended to look, injecting other techs, then you're not being very honest about the language. – MrMesees Dec 17 '17 at 18:10
2

This will depend a lot on the compiler, programmers, whether it has gc and can vary too much. If it is compiled directly to machine code then expect to have better performance than interpreted most of the time but there is a finite amount of optimization possible before you have asm speed anyway.

If someone said fortran was slightly faster would you code a new project in that anyway?

Tim Matthews
  • 5,031
  • 8
  • 38
  • 45
  • No of course not :) I am more curious about what could possibly make it faster -- maybe it's less expressive so it can make more assumptions/optimizations, that sort of thing. I dont know fortran. –  Mar 04 '09 at 12:59
2

You must be using some odd managed XML parser as you load this page then. :)

We continously profile code and the gain is consistently (and this is not naive C++, it is just modern C++ with boos). It consistensly paves any CLR implementation by at least 2x and often by 5x or more. A bit better than Java days when it was around 20x times faster but you can still find good instances and simply eliminate all the System.Object bloat and clearly beat it to a pulp.

One thing managed devs don't get is that the hardware architecture is against any scaling of VM and object root aproaches. You have to see it to believe it, hang on, fire up a browser and go to a 'thin' VM like Silverlight. You'll be schocked how slow and CPU hungry it is.

Two, kick of a database app for any performance, yes managed vs native db.

rama-jka toti
  • 1,404
  • 10
  • 16
1

It's usually the algorithm not the language that determines the performance ballpark that you will end up in.

Within that ballpark, optimising compilers can usually produce better code than most assembly coders.

Premature optimisation is the root of all evil

This may be the "common knowledge" that everyone can parrot, but I submit that's probably because it's correct. I await concrete evidence to the contrary.

Anthony
  • 5,176
  • 6
  • 65
  • 87
1

C# is much faster than C++ - in C# I can write an XML parser and data processor in a tenth the time it takes me to write it C++.

Oh, did you mean execution speed?

Even then, if you take the time from the first line of code written to the end of the first execution of the code, C# is still probably faster than C++.

This is a very interesting article about converting a C++ program to C# and the effort required to make the C++ faster than the C#.

So, if you take development speed into account, almost anything beats C++.

OK, to address tht OP's runtime only performance requirement: It's not the langauge, it's the implementation of the language that determines the runtime performance. I could write a C++ compiler that produces the slowest code imaginable, but it's still C++. It is also theoretically possible to write a compiler for Java that targets IA32 instructions rather than the Java VM byte codes, giving a runtime speed boost.

The performance of your code will depend on the fit between the strengths of the language and the requirements of the code. For example, a program that does lots of memory allocation / deallocation will perform badly in a naive C++ program (i.e. use the default memory allocator) since the C++ memory allocation strategy is too generalised, whereas C#'s GC based allocator can perform better (as the above link shows). String manipulation is slow in C++ but quick in languages like php, perl, etc.

Skizz
  • 69,698
  • 10
  • 71
  • 108
1

D can sometimes be faster than C++ in practical applications, largely because the presence of garbage collection helps avoid the overhead of RAII and reference counting when using smart pointers. For programs that allocate large amounts of small objects with non-trivial lifecycles, garbage collection can be faster than C++-style memory management. Also, D's builtin arrays allow the compiler to perform better optimizations in some cases than C++'s STL vector, which the compiler doesn't understand. Furthermore, D2 supports immutable data and pure function annotations, which recent versions of DMD2 optimize based on. Walter Bright, D's creator, wrote a JavaScript interpreter in both D and C++, and according to him, the D version is faster.

dsimcha
  • 67,514
  • 53
  • 213
  • 334
  • Shouldn't the garbage collection logic apply to other grabage collected languages like Java and C# ? – Nikhil Mar 09 '09 at 03:46
  • Yes, and these languages can also sometimes be faster than C++, but D is more often because it has less overhead in other places. – dsimcha Mar 09 '09 at 03:56
  • What about BLADE? Has that ever been benchmarked against blitz or fortran? – Ellery Newcomer Mar 09 '09 at 04:27
  • It was a library that took advantage of the compile time programming features of D to produce allegedly near-optimal X86 floating point code. I don't know what its current status is, but it generated a lot of interest a few years ago. – Ellery Newcomer Mar 10 '09 at 16:22
  • Today BLADE should be outperformed by LDC compiled code by a large margin because LDC can vectorize and use SSE/AVX with the typical LLVM optimizations – Quonux Nov 12 '18 at 21:00
0

It all depends on the compiler, take for example the Stalin Scheme compiler, it beats almost all languages in the Debian micro benchmark suite, but do they mention anything about compile times?

No, I suspect (I have not used Stalin before) compiling for benchmarks (iow all optimizations at maximum effort levels) takes a jolly long time for anything but the smallest pieces of code.

leppie
  • 115,091
  • 17
  • 196
  • 297
0

Performance of a compiled language is a useless concept: What's important is the quality of the compiler, ie what optimizations it is able to apply. For example, often - but not always - the Intel C++ compiler produces better performing code than g++. So how do you measure the performance of C++?

Where language semantics come in is how easy it is for the programmer to get the compiler to create optimal output. For example, it's often easier to parallelize Fortran code than C code, which is why Fortran is still heavily used for high-performance computation (eg climate simulations).


As the question and some of the answers mentioned assembler: the same is true here, it's just another compiled language and thus not inherently 'faster'. The difference between assembler and other languages is that the programmer - who ideally has absolute knowledge about the program - is responsible for all of the optimizations instead of delegating some of them to the 'dumb' compiler.

Eg function calls in assembler may use registers to pass arguments and don't need to create unnecessary stack frames, but a good compiler can do this as well (think inlining or fastcall). The downside of using assembler is that better performing algorithms are harder to implement (think linear search vs. binary seach, hashtable lookup, ...).

Christoph
  • 164,997
  • 36
  • 182
  • 240
  • Well.. consider the speed of the language to be its best under any compiler. I'm not splitting hairs here. It's easier to parallelize Fortran code? Interesting :) so fortran has something in common with FP. –  Mar 04 '09 at 13:20
0

if the code is not written for performance then C# is faster than C++.

A necessary disclaimer: All benchmarks are evil.

Here's benchmarks that in favour of C++.

The above two links show that we can find cases where C++ is faster than C# and vice versa.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • The article you linked to only seems to analyze the memory performance of the system, NOT the speed of the program. While it looks like the code measures timings, i can't actually find any reference to the times recorded. Further more, this is also bringing in other areas such as hard disk access. – Grant Peters Mar 04 '09 at 13:28
  • 1
    Well, the first is a rather special case that performs notoriously badly in C++ for two main reasons. Forming a general conclusion from it like you do (“if the code is not written for performance then C# is faster than C++”) is IMHO misleading or even wrong. – Konrad Rudolph Mar 04 '09 at 13:35
  • @Grant Peters: It analizes both time and memory e.g., try to click on "Analyzing the managed code" from the above link. See http://stackoverflow.com/questions/385297/whats-wrong-with-c-compared-to-other-languages/385351#385351 for the description of the above link. – jfs Mar 04 '09 at 13:39
  • @Konrad Rudolph: It is so obvious that I even haven't included the disclaimer initially. I find it ridiculous to talk about fast *languages* without specifying application domain. – jfs Mar 04 '09 at 13:55
0

Doing much better than C++ is mostly going to be about making the compiler understand what the programmer means. An example of this might be an instance where a compiler of any language infers that a region of code is independent of its inputs and just computes the result value at compile time.

Another example of this is how C# produces some very high performance code simply because the compiler knows what particular incantations 'mean' and can cleverly use the implementation that produces the highest performance, where a transliteration of the same program into C++ results in needless alloc/delete cycles (hidden by templates) because the compiler is handling the general case instead of the particular case this piece of code is giving.

A final example might be in the Brook/Cuda adaptations of C designed for exotic hardware that isn't so exotic anymore. The language supports the exact primitives (kernel functions) that map to the non von-neuman hardware being compiled for.

SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
0

Is that why you are using a managed browser? Because it is faster. Or managed OS because it is faster. Nah, hang on, it is the SQL database.. Wait, it must be the game you are playing. Stop, there must be a piece of numerical code Java adn Csharp frankly are useless with. BTW, you have to check what your VM is written it to slag the root language and say it is slow.

What a misconecption, but hey show me a fast managed app so we can all have a laugh. VS? OpenOffice?

rama-jka toti
  • 1,404
  • 10
  • 16
0

Ahh... The good old question - which compiler makes faster code?

  1. It only matters in code that actually spends much time at the bottom of the call stack, i.e. hot spots that don't contain function calls, such as matrix inversion, etc.

  2. (Implied by 1) It only matters in code the compiler actually sees. If your program counter spends all its time in 3rd-party libraries you don't build, it doesn't matter.

  3. In code where it does matter, it all comes down to which compiler makes better ASM, and that's largely a function of how smartly or stupidly the source code is written.

With all these variables, it's hard to distinguish between good compilers.

However, as was said, if you've got a lot of Fortran code to compile, don't re-write it.

Mike Dunlavey
  • 40,059
  • 14
  • 91
  • 135