Font Size

Profile

Layout

Cpanel
Jake Stine_avatar

C++ exceptions can be an optimization

One of the first things I sought to do when I first started contributing to PCSX2 was to improve the emulator's overall stability and error handling; and to this day it's still one of my top priorities.

My method of doing so was initially seen as controversial: I merged in drk||Raziel's VTLB code (which was C++), converted the rest of the PCSX2 codebase to C++, and started replacing the (lack of?) error code return values with modern C++ exception handling. The initial reaction from the public (and some PCSX2 team members) was either distrust or panic. Chants of "C++ is slow!" or "Exception handling is slow!" frequented the PCSX2 revision comments.

And admittedly, for some tasks and in some specific scenarios, C++ and it's exception handling are slow. But, of course, the key is to avoid those scenarios... which as it turns out is really quite easy. Better yet, clever use of C++ and its exceptions can actually be a speedup. How is that possible? I'll explain!

Typically in traditional error handling models, you check the return code of a function for errors, like so:

Code:
if( DoSomethingSpecial() == SPECIAL_FAIL )
{
    // Handle error.
}


This is simple, short, and quite fast compared to the overhead of entering a C++ try/catch block. But let's consider a more practical everyday example:

Code:
int DoSomethingSpecial()
{
    if( DoSomethingElse() == SPECIAL_FAIL ) return SPECIAL_FAIL;

    // Do stuff based on DoSomethingElse's success
    Console::WriteLn( "Success!" );

    return SPECIAL_WIN;
}

void LoopOfCode()
{
    do
    {
        // code [...]
    } while( DoSomethingSpecial() != SPECIAL_FAIL )
}


The above code snippet must perform no less than two conditional checks per loop just to propagate the error code up the chain of function calls, and this isn't even handling the possibility of a function returning more than one error code yet! This is a situation where C++ Exception Handling can come to our rescue:

Code:
void DoSomethingSpecial()
{
    DoSomethingElse();

    // Do stuff based on DoSomethingElse's success
    Console::WriteLn( "Success!" );
}

void LoopOfCode()
{
    try
    {
        while( true )
        {
            DoSomethingSpecial();
        };
    } catch( Exception:: SpecialFail&& )
    {
    }
}


The above C++ snippet performs the exact same operation, except now no conditionals are needed. We've traded off the two conditionals per loop for the entry/exit code for the try/catch block. But the block is outside the loop, so it will be run only once. Conditional checks are one of the slower operations on almost any CPU design, which means if the loop is a busy one which spins frequently this C++ code will certainly be a significant speedup over the plain jane C version. And that's just with one return code. Adding multiple exception handlers doesn't impact performance at all, so in a case where there are multiple return codes the C++ exception handling approach shines even brighter.

... thus dies the age-old rumor that C++ is slower than C. IT's all in how you wield your sword. Or... well... programming language.

Edit: I should add that the basic theory of optimization I'm using here is what I call "optimizing for the common case." It's a process of speeding up the code that's being run more frequently (which in our example above is a typically error-free running loop) by offloading the logic to an area of the code that's run much less frequently (the exception handler's entry/exit overhead). It's one of the most powerful optimization techniques any programmer can employ.

Jake Stine_avatar

The DevBlogs now allow user comments!

If you'd like to make comments or ask questions in response to a devblog entry you can now do so from the PCSX2 Public Forums. Yes, unlike some frivolous free-for-all blog with a thousand disgusting comment spams, our DevBlog requires that you must be a registered user and logged in to post.

It might not be the best system in the world, but it works well enough for our needs.

This is part of the PCSX2 Team's continuing attempt to expand the horizons of open source PS2 emulation development. There is a new dedicated developers forum on our Forums that centralizes discussions relating to PCSX2 design and development; Svn updates and announcements, Compilation issues, Cross-platform development, patch/bugfix submissions, and probably more to come.

The new forum is not meant for general bug reports or whimsical complaints. So to keep things clean and focused, new topics can only be created by forum administrators and PCSX2 developers. We will create topics relevant to the projects we're focusing on and the public can offer your input via replies. And well... we'll just see how things pan out from here... Smile

Click to Leave a Comment!

cottonvibes_avatar

The Pros and Cons of GoogleCode

As most of you know we use Google Code for our Public SVN repository, and doing so has its pros and cons.

One of the coolest features of Google Code is that it allows people to rate and comment on revisions. This is great for bug tracking and getting a quick consensus of what people think about the revision.

In order to get quicker responses and have a wider degree of testing/comments, we have granted public access for comments/ratings/issues. This is extremely helpful because as a small team, we don't have the time nor the man-power to constantly test every revision, therefor we count on the public to test for us, and inform us on things we may not know. Furthermore, we have also gained new coders and contributors through their comments/issues on GoogleCode.

There is a huge downside to this open-environment however; the most notable one being the trolls. Like with most public sites on the internet, we have our share of trolls. People giving negative ratings to a bunch of irrelevant revisions because they're mad their game broke. Or people leaving spam (even threatening) comments. Or best of all, people repetitively saying that game XYZ doesn't work on every revision, and telling us to fix it.

A great example that I have to mention here is This email address is being protected from spambots. You need JavaScript enabled to view it. (go ahead and spam his email if you want, he spams our svn). He has made dozens of comments telling us to fix GT4/3, and always complains when we ignore him. At this point he's started to just rate revisions negatively without even leaving a comment as to why. Sometimes I wonder if these people just think we're purposely not making games work because we're evil or something...

Now you might just be wondering, "So, why don't you just ban the guy."
Well this is the biggest problem with GoogleCode, currently there's no way to just ban users from your SVN. We can either make public access to comments/ratings/issues, or we can make it only available to project members. There's no way to have it public while banning the trolls like ferrarinews.

Anyways, there's more to GoogleCode than what I talked about here, but I think i described the main issue we've been having with it Smile

Jake Stine_avatar

Measuring the Benefits of wxWidgets

One of the major changes planned for the next release of PCSX2 is a complete overhaul of the gui/frontend, switching from the current "native" Windows/Linux interfaces to a single unified interface that's (more or less) the same for both platforms. To make such a grand vision possible we needed the help of a third party gui tooolkit, from which there were several to choose from. After much consideration we settled on wxWidgets, which is the same toolkit used by a few other notable emulators, such as Dolphin.

So what are the benefits of the new PCSX2 interface in development?

1. A vastly improved Linux interface.

... and not just in terms of what you see, but how the emulator cooperates with the operating system as a whole. wxWidgets provides dozens of very useful cross-platform tools that are much more well-suited to Linux functionality than the current PCSX2 codebase. The new interface will have a smarter plugin loader, and multilingual support as well. It will also be easier to install and run as a user other than root.

2. Windows XP/Vista Themed appearances will finally work!

Until now, PCSX2 used the old Win95 ASCII-based Common Controls libraries, and this forced Windows to disable themes support when rendering the PCSX2 interface. Buttons were plain and unshaded, and dialog boxes such as the File and Folder pickers were small, ugly, and lacking in features. All of this will be fixed in the next release.

3. More complete internationalization support.

Translations of the PCSX2 interface will be easier to make and maintain, and shouldn't become broken or obsolete from program updates, which was a persistent problem in the older PCSX2 interface design. In addition, PCSX2 will be fully Unicode compliant on both Windows and Linux platforms, which should help resolve various oddball problems the emulator may have encountered on non-English operating systems.

4. A more responsive multithreaded interface which will remain fully accessible even while games are running!

The new interface will run on its own thread separate from the emulator's EE/MTGS threads, allowing it to remain open and accessible in the background, without the need to shut down the GS window. This should improve the stability of "pausing" emulation, and also opens the door for expanding on interface integration; such as binding popup menus, toolbars, status bars, or other useful things to the GS window.

Furthermore, if a game deadlocks the system, the interface will usually remain responsive even as the rest of the emulator freezes up (which might not be much of a feature for end users, but is quite handy for us developers).

5. The Teaser Image!

And here's a sneak peek at the current GUI-Work-in-Progress:

... yeah it's not a whole lot to see yet -- I might post some more as development progresses.


From a coder's perspective:

In all the wxWidgets experience so far has been a decent one. There are a few annoyances, but those tend to be more the fault of cross-platform considerations (some things are not supported well under Linux, or vice versa), or more commonly due to limitations and design flaws in the C++ language itself rather than of wxWidgets (in particular, C/C++ make it especially difficult to work with unicode strings in a 'nice' way). For the most part wx tries to model itself in the image of the .NET Framework and Java Framework API designs, which are good designs to follow.

Jake Stine_avatar

A Moment of Zen

While not likely to win the prize of being featured in PCSX2's next release (presumably 0.9.7, but you can never be too sure), this logo might deserve honorable mention. I present for you a moment of Zen:

pcsx2 JC version

... is that an exploding cheeseburger on his robe?

You are here: Home Developer Blog