views:

1032

answers:

15

I was just wondering why c++ ist that powerful and performant for developing games. I wrote a lot of games in c# and delphi, always using the timer component to make objects "move". Another option for the movement were loops, but they are definitely not performant.

So what technique does c++ use that users can develop performant games?

+12  A: 

To a large extent this is based on two things:

  • History
  • Current frameworks

For many years, C++ was the only* choice for high-performance applications of any kind, including games. As a result, there were significant investments into game engines and libraries that were also written in C++.

Even today, most frameworks for gaming are written in C++. XNA does allow C#, but even Microsoft keep pushing C++ as their language of choice.

*yeah, it's subjective...

GalacticCowboy
Well, it's not subjective. Actually plain C is faster in many situations, and hand-coded assembler is faster. The only way to go faster is to design and build your own special-purpose processors :)
luiscolorado
@luis: Just saying that C is faster in many situations is not objective either.
Georg Fritzsche
with all respects, XNA sucks!
Vimvq1987
@georg - Agreed - C is faster than C++ *if* you use C++ features for no good reason, just because they're there. For example a virtual method is a way to build a which-implementation dispatch decision into the call. If you don't have that language feature, the decision has to be coded some other way - which can easily be slower than virtual dispatch. Of course that dispatch cost is so small that, outside of critical inner loops, you probably don't care about it anyway.
Steve314
Actually, the word **only** was what I highlighted as subjective. As in, there were other choices but it was the most widely used and almost expected.
GalacticCowboy
@Georg Fritzsche: Georg, please let me know of some specific examples or statistics that show that, other things being reasonably equal, a program executed **faster** in other language than C (with the obvious exception of assembly programming and C++).There is no subjectivity here. There are many reasons why C is faster. I am seriously eager to hear your response. I might learn something new!Luis
luiscolorado
@luis: It really depends on the situation at hand - language support for higher-level patterns (-> more optimization opportunities), runtime-optimizations (e.g. Java) would be two possible factors that come to mind. If you say C is faster in *many* situations, you should have to back that up ;) Going in details would be off-topic here anyway, if you're curious you could open a new question (if that wasn't asked already).
Georg Fritzsche
@Georg: And speed would also depend heavily on the programmer and the programming style. In some cases C/C++ beats Java, and vice versa; here are some examples: http://www.idiom.com/~zilla/Computer/javaCbenchmark.html, http://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2BUnfortunately, the benchmarks are kind of old, and they compare gcc vs javac. I could not find benchmarks using Microsoft C compiler versus Java. And, unfortunately, benchmarks are highly biased.So, what is the best approach? As usual, it has to depend on the situation at hand.
luiscolorado
So is it subjective or not? ^_^ Your entire argument seems to be, "It's not subjective, except in situations where it is."
GalacticCowboy
@luis: Please make it a new question (if you can't find a similar one that is).
Georg Fritzsche
+2  A: 

nothing stops you to use a timer to write your c++ games.

You can look into C++ Boost thread::sleep method to do that.

http://www.boost.org/doc/libs/1_38_0/doc/html/thread/thread_management.html#thread.thread_management.thread.sleep

rodrigob
+15  A: 

C++ give you finer grain of control over the actual hardware and bit pushing. For common business needs, a third generation language such as Java or C# is quicker to program and takes worries like pointers and garbage collection off the hands of the developer. This is at a cost of lack of ability to optimize and fine tune how memory and data structures are used.

You can also take a hybrid approach of breaking the game into a higher level language for scripting etc and then "drop" into C++ land for parts that require the speed and optimizations.

Kenoyer130
Are Java and C# really 4th generation languages?
nikie
I also have in mind they are 3GL. 4GL is more specific on a special task to use them for, e.g. querying databases -> SQL
ApoY2k
The only reason why everybody is using c++ is the same reason why everybody is using WinForms. Because everybody uses it :)
Blub
There are commercial games written in Java and C#. Java - IL2 sturmovik. C# is apparently being used by electronic arts in The Sims 3. I prefer C++ and dislike both Java and C#, but they were already used for game development, so "where real time responses are expected" is incorrect argument.
SigTerm
I use WF because I have to. I couldn't say I like it...
ApoY2k
@nikie - the term fourth generation language was used for marketing database languages. Forth misspelled deliberately the and That. That left general purpose languages with nowhere to go after the third generation. And lets face it, C# and Java aren't really that different to a whole load of imperative languages that were available in the 80s, perhaps even the 70s. Classes and garbage collectors weren't invented yesterday. In my view, we're very much still in the third generation of programming languages.
Steve314
@SigTerm - garbage collection is a concern for hard real-time. However, games aren't really "hard" real time, and there are garbage collection algorithms that are well-suited to soft real time (and maybe hard real time too, though I'm less sure of that). The problem is you don't necessarily know what VM (and thus what GC) the end user will be using, and whether that will be appropriate. Games players hate even short GC delays - they destroy the flow of the game. Still, custom allocators can probably avoid these issues, or limit them to level-loading times.
Steve314
IL-2 Sturmovik is actually a hybrid of Java and C++. So it may not be the best example... The main game is written in Java, but uses C++ for rendering.
GalacticCowboy
@GalaticCowboy - adding to that, custom domain-specific languages are quite common for game logic and level design. Java would seem to be competing, in that particular case, with clunky improvised scripting languages where no-one much cares that much about performance because it never goes anywhere near performance-critical functionality.
Steve314
+2  A: 

OpenGL and DirectX are both very compatible with C++. Add in the fact that you have more fine grained control over memory, memory allocation, and you can use just enough features of C++ to make development "easier" than straight C to get some of the reasons.

wheaties
+9  A: 

So what technique does c++ use that users can develop performant games?

None that are not (also) found in other languages.

The advantage of C++ over other languages (subjective to a degree) is not in the techniques used.

It is a combination of a few factors, making it both low-level enough and high-level enough for what is needed:

  • it is deterministic (you can determine what gets executed when). This is not true for garbage collected languages and it is not (or partially) true for languages run in virtual machines.

  • it offers high performance (you can get C-like performance and even drop in some assembly code if you feel like it).

  • it offers enough abstraction to be higher level than other fast languages (like C for example).

In the end it is something close to both low-level languages and high-level languages.

utnapistim
It used to be that the best games were written even in assembler because you had to use every drop of power of the CPU. Today, CPU's are very powerful, and relatively simple games can be developed using Java, C#, or even BASIC. But, if you want to develop the very best games, you still want to use the fastest languages you can use.
luiscolorado
There are a lot of other languages that do not offer the techniques of "no garbage college", "hand-tuned data structures", "inline assembly".
Paul Nathan
@luiscolorado - the "power to waste" view is a bit one-sided. The complexity increased too, and the algorithmic optimisations became more important than cycle-counting. A high-level language allows you to develop more sophisticated algorithms and data structures in the same time-scale, meaning a complex C++ module. will probably be much faster than another module written in assembler in the same time. Trimming a few cycles per iteration off your collision code will not compete with a more sophisticated algorithm, for instance, and there's a *lot* of collision detection theory out there.
Steve314
@Steve314, you are right. Just using the fastest languages doesn't guarantee you the fastest performance, or development time.Please consider that I am not necessarily advocating necessarily for assembler, C, or C++. If development time/money are not abundant, "early optimization" is a mistake. It is just better to replace the bottlenecks with better algorithms or using a faster language.
luiscolorado
@luiscolorado: "if you want to develop the very best games, you still want to use the fastest languages" This is incorrect. A lot of things are being offloaded from CPU onto something else. Graphics, Physics(nvidia chips), sound (hw-dependent), and a lot of code you use was written by other people (source n/a). We aren't in the dos era anymore, and CPU isn't always the most important factor, so performance depends on how well you utilize power of other chips. I.e. you can write game in fastest language, but still screw up and get 1 fps because you haven't optimized your interaction with GPU.
SigTerm
@SigTerm I would say that it is atleast just as likely that you'll screw up and get 1 fps with a language that is not as performant as C++. On the other hand, you'll probably get a lot faster work-iteration times.
Simon
+2  A: 

From what I've always understood, and the rule applies to sports as well.

Speed kills.

All about speed.

Jack Marchetti
So *thats* why "the accelerator" sounds like a character out of an 80s action film.
Steve314
+4  A: 

There is a solid codebase for games, and it's mostly in C++. Most game engines are implemented in C++ and that's because as someone previously mentioned also OpenGL and DirectX are implemented in C++. Further on, games always push the limits of hardware and that's why the code needs to be as fast and optimal as possible..

On the opposite side there are the office/business applications that simply need faster development cycles, stability and to be as extensible as possible.

John Paul
+1  A: 

The strength of C++ when it comes to game development is the ability to exactly layout the data-structures that your software will use. When performant real-time systems (such as games) started growing, it was the most commonly supported and most developed programming language. As such it was a natural choice for games that try to push platforms to their limit. This has in term lead most developers to go along with this choice even if they need it or not.

C++ provides the ability to override important performance bottlenecks such as memory allocation. It has the ability to structure and place things exactly where they want in the memory. On top of this it's a flexible programming language that provides a decent development velocity.

Simon
+6  A: 

C++ has the combination of efficiency and abstraction that makes it still the only practical choice for large-scale systems that require efficient responses[1].

Hardware interface layers are, as a general rule, in C or C++ as well, meaning a foreign language interface does not have to be set up to talk to the hardware abstraction layers.

Further, it has the advantage of a large community experienced in writing games, as well as numerous frameworks.

On a personal note, I have used games written in other languages, and they have consistently been slower.

[1] Ada or Delphi may also be usable in this area, but their popularity level means it's not as pragmatic to choose them unless you have a niche need.

Paul Nathan
Plus, the C/C++ code optimizers developed by Microsoft are unbelievable. I doubt (but I may be wrong) that so much re$ource$ and ingenuity have been spent on Ada or Delphi.
luiscolorado
@luis: What I've heard is that `icc`, the Intel C++ compiler, beats the pants off Microsoft's compiler.
Paul Nathan
@Paul: that is good to know. Watcom, at one point, also beat Microsoft. But, the point is the same: compilers are being built smarter to optimize code, and the trend will probably continue (IMHO).
luiscolorado
"Ada or Delphi" The first game enigine I ever worked on was a spacesim written in delphi with DirectX bindings. We had a 1500 fps reports. If you aren't using "heavy artillery" (i.e. something language-specific that negatively impacts performance) of the language, it doesn't really matter what you're using. I wouldn't use interpreted language such as python, though.
SigTerm
@luiscolorado: "Plus, the C/C++ code optimizers developed by Microsoft..." Last time I used delphi compiler (5 to 7 years ago, delphi 6 or 7) it was significantly (10x times or more) faster than any C++ compiler I ever saw and produced very small executables (well, if you get rid of VLC). I was quite amazed first time I built C++ project on VC6 - I literally could drink few cups of tea during compilation, while with Delphi rebuilding everything was quick way to check for syntax errors (building project few times per minute was normal). Do not quickly disregard tool if you haven't used it.
SigTerm
@luiscolorado: And another thing. I wouldn't select a tool solely because of amount of time and resources spent on it. Those qualities are not important. What is important is compatibility with libraries and tools. And in this part Delphi loses. Literally everything you should interface with was written in C or C++ - import/export plugins for 3dsmax or maya, for example. While you still can use delphi in for many tasks, eventually things will get too tricky to handle. For example, it is theoretically possible to make Delphi class that has C++ class as ancestor, but I wouldn't do that.
SigTerm
@Sigterm: I muck about with a 3d python game occasionally - it's hideously slow. It even has DirectX interface. Also, fyi, Pascal was designed to have a single-pass compile. C++... let's just say it can't do that. :-)
Paul Nathan
+1  A: 

Games is performance critical software that requires 100% usage of the hardware user has, and C++ is only popular language that gives you such abilities:

  • High abstraction level - fine Object oriented programming and generic programming
  • Very good and deterministic control of the resources you use.
  • Ability to optimize special parts to very high level that is almost impossible to achieve with other popular languages.

For this reason you will find C++ not only in game development but also in many other areas that require from you best performance, lowest resource usage and good ability to optimize like, for example, data bases, system programming and many other areas.

Artyom
+2  A: 

Some other aspects that I think weren't mentioned:

  • Game developers often devote time for optimizing code. The right tools are there for this with C++. Eg. most compilers support intrinsic functions, so it's possible to use SSE instructions directly. Another thing that game programmers often do is inspect the generated assembly, and tune the C code accordingly, eg. to eliminate dynamic branches. Avoiding virtual functions can also bring speed benefits.
  • Garbage collection - it can be unfortunate if the game halts for a moment for garbage collection. For a console game that is meant to run at 30 or 60 fps, this can be a problem. There are now generational garbage collectors in many languages, so the problem is less severe now than it used to be.
  • It is in fact more cross-platform than C# or Java from a game developer's perspective. Can you run Java or C# on PS3?
Cornelius Scarabeus
Java - probably; C# - probably not. :)
GalacticCowboy
Then will MS use Java on the Xbox? No, there goes your portability ;)
Ivo Wetzel
You never know... after all, Microsoft is not using C# to develop their operating systems :) ... and how many kids care about what's running in their consoles :)
luiscolorado
@GalacticCowboy: There is a lot of stuff for Cell, I forgot about that - but not necessarily available on the PS3 for games.I'm not familiar with how virtual machines work, but doesn't JIT compilation require code generation? - Well, that is generally not allowed on these platforms due to security reasons.
Cornelius Scarabeus
JIT is not "code generation" in the sense of emitting arbitrary code. The code is already compiled to an intermediate language; the JITter just emits the corresponding machine language.
GalacticCowboy
@GalacticCowboy: That was also my understanding, ie. exactly what can't be done, you can't execute an arbitrary part of memory, and also can't set it to be executable. Such things area disabled to prevent hacking of the console.
Cornelius Scarabeus
+1  A: 

As machines become more powerful and more of the workload is shifted to hardware (graphics and even physics, in some cases), there are more system resources available to perform other tasks. As such, even though C++ is still the industry standard, the down-to-the-metal optimizations it enables are no longer the main reason it's used. The main reason it's used is that the majority of APIs for game development are C++ APIs. You rarely want to write your own engine and even if you write your own engine, you're likely reusing standard low-level components, such as NVidia PhysX, DirectX, OpenGL, etc. Some of these now have Managed code interfaces, but the core APIs are for C++, since it is so commonly used.

Another trend worth noting is that a lot of games these days use scripting languages, such as Python or Lua, to control much of the game logic. This gives your content developers and modders flexibility to provide rich behaviors without having to code in C++ or build. Scripting is not super high-performance, but it's extremely convenient and modern PCs have plenty of horsepower to handle the scripting.

Dan Bryant
"As machines become more powerful and more of the workload is shifted to hardware." This is partially true today. It is true that machines like consoles, laptops and desktops are very powerful today, but we also need to consider those less powerful machines like smartphones, which may require coding "closer to the metal" in certain situations.
luiscolorado
@luiscolorado, phones are a whole different arena, but definitely worth considering. Most phone games are actually either in Objective C or Java these days, targeting iPhone or Android respectively. If the Windows 7 phone gets any market share, that will open the door for mobile games on Silverlight, likely using C#.
Dan Bryant
+1  A: 

There are a number of reasons here.

  1. Portability
    Does one really think that Sony will use C# in one of their consoles? Will Nintendo deploy a JVM on the Wii2?

    No.

    What if Microsoft goes C# with the next Xbox? Guess what, they won't. That would double the Codebase for all 3rd Party Developers, rendering Microsofts new console much less attractive to develop for.

    So C++ is the obvious choice here because one just needs the compiler for the appropriate architecture.

  2. Performance
    Also the core of 3D engines will most likely always be written in C/C++ with part of it in ASM, simply due to the fact that you want to squeeze out every bit of performance on Consoles where your environment is basically hammered in stone.

  3. Development Time
    Before all the licensable engines came up, there was a time when the fist generation of software titles took extremely long to develop, just because you had to write a whole new engine for your Game on the new Platform, which takes time. Taken into account that the development of a big game already takes years, this costs lots of money. So it was always easier to take existing code and "upgrade" it for the next generation. Then over time you would gradually improve it. Bearing that in mind, it's easy to see that none of the console manufacturers wanted to make their developers face even longer development times by switching their console to something different than C/C++.

So to wrap it all up. Portability, performance and legacy code bases are the reasons that C/C++ is still THE major player in game development.

Ivo Wetzel
You can code within the XNA framework in C# and deploy to the current Xbox 360. In fact, you've been able to target the Xbox with C# for several years now. Undoubtedly this will continue to be supported with the next generation Xbox as well. I also wouldn't be surprised if it supports Silverlight for web-based casual games.
Dan Bryant
Yes, but no one will create a 20 Million Dollar+ Project with this, it's mainly for smaller Games that get release on both Xbox and Windows. If you're after the big money, there's no way around C/C++ ATM.
Ivo Wetzel
A: 

The only technique that C++ has over most other high level languages is that "you don't pay for what you don't use". The language doesn't have features behind the scenes like garbage collection, reference counting, synchronisation, reflection, introspection, bounds-checking, run-time type checking, meta-classes, and so on, each of which can impose a cost on general operation.

Of course, most of those features are very useful, so in C++ you have to spend a lot more coder time to get the same results. Whether it's worth the effort or not tends to come down to a matter of how much legacy code you have to work with.

Kylotan
+1  A: 

I'd like to point out a few things that people are missing. Firstly C++ has it's dominance in the industry because most studios have an existing code C++ 3D engine. Secondly they built it or have been working with it for years. Just those two points alone make it reasonable to stay with C++. Thirdly native C++ will always be slightly faster than managed languages because it doesn't have the overhead of being.. well, managed.

Now be aware however this is for existing game studios, the indie scene is a little difference and I think that here is where XNA is actually picking up speed. Firstly it lets gives you access to three devices (pc, xbox, zune based) and that's not even including mono xna. The speed differences are almost never worth worrying about at this level and it's just more productive.

I hope I've given you something to consider.

Lavinski