mercredi 29 avril 2015

Why don't throw() and noexcept have any overhead

throw() was added in C++03 as an exception specifier, however it was deprecated in C++11 for the noexcept specifier.

After profiling some code to find the speed of code using throw(), noexcept and just plain functions I found that all of them had roughly the same time for the function call.

Results:

throw()       noexcept      plain old function
11233 ms      11105 ms      11216 ms
11195 ms      11122 ms      11150 ms
11192 ms      11151 ms      11231 ms
11214 ms      11218 ms      11228 ms

compiled with MinGW using g++ -o test.exe inc.cpp no.cpp -std=c++11 -O3

Here is the code I use to for profiling:

int main() {
    unsigned long long iter = (unsigned long long)1 << (unsigned long long)40;
    auto t1 = std::chrono::high_resolution_clock::now();

    for(unsigned long long i = 0; i < iter; i++)
    {
#ifdef THROW
        throw_func();
#elif defined NOEXCEPT
        noexcept_func();
#else
        std_func();
#endif
     }

     auto t2 = std::chrono::high_resolution_clock::now();

     std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << " ms" << std::endl;
}

The functions are defined as:

unsigned long long val = 1;

struct exception {  };

void throw_func(void) throw()
{
    if (!val++)
       throw exception();
}
void noexcept_func(void) noexcept
{
    if (!val++)
        throw exception();
}
void std_func(void)
{
    if (!val++)
        throw exception();
}

I was surprised by these results because I was under the impression that throw() and noexcept added some overhead to the function.

Why don't throw() and noexcept add any overhead to the function call as compared to the regular function call?

Aucun commentaire:

Enregistrer un commentaire