Exceptions in C++

Are exceptions slower than constructions with ‘return’?

Yes, exceptions are slower, just a bit.

Test setup

The test-program first wastes some CPU time in a recursive function and using a loop. This is to simulate a real-time CPU-intensive task which has deeply nested functions. This process runs twice, first with high values of looping and recursing and another time with no looping and no recursing. Then the program prints the time spent and the ratio between throwing/nonthrowing functions on both runs.

Results

Typical output of the program:

ratio throwing/nonthrowing: 3.09256e+06ms / 3.07183e+06ms = 1.00675
ratio throwing/nonthrowing: 3ms / 3ms = 1

Normally, the program doesn’t throw, but does try to catch exceptions because we want to know the performance of the situation where nothing goes wrong. If something does go wrong (and an exception is thrown) the following output may be observed:

ratio throwing/nonthrowing: 3.16843e+06ms / 3.16829e+06ms = 1.00005
ratio throwing/nonthrowing: 42ms / 3ms = 14

Conclusions

Apparently, actually throwing an exception does cost some time, but when everything is ok the performance is a tiny bit slower: about 0.65%, calculated from the test run.

Notes

The program was compiled and tested on an Athlon 900Mhz, with the following command:

g++ -o exceptions exceptions.cc -O3

Apologies for the ugly code :)

Comments are closed.