samedi 6 octobre 2018

constexpr specifier performance did't meet my expectations in C++

I has just learned that constexpr specifier function can run in compiling process, I tried to check the actual performance in VS 2017 with Debug x86 Mode, the result showed that a tiny time difference between them.It still elapsed much time rather than "0". Did I do something wrong and could anyone help me,thanks a lot!

#include <iostream>
#include <time.h>

size_t r_fun(size_t n) noexcept
{
    if (n == 0) return 0;
    if (n == 1) return 1;
    return r_fun(n - 1) + r_fun(n - 2);
}

constexpr size_t c_fun(size_t n) noexcept
{
    if (n == 0) return 0;
    if (n == 1) return 1;
    return c_fun(n - 1) + c_fun(n - 2);
}


int main()
{
    clock_t start, finish;

    start = clock();
    auto r_x = r_fun(40);  
    finish = clock();
    std::cout <<"result:"<< r_x<< "\ttime:" << (double)(finish - start) << std::endl;

    start = clock();
    static const auto c_x = c_fun(40);
    finish = clock();
    std::cout << "result:" << c_x << "\ttime:" << (double)(finish - start) << std::endl;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire