I wrote the following code to test the time taken for a constexpr factorial to evaluate vs normal way
#include<iostream>
#include<chrono>
constexpr long int factorialC(long int x){ return x*(x <2?1 : factorialC(x-1));}
using ns = std::chrono::nanoseconds;
using get_time = std::chrono::steady_clock;
void factorial(long int x){
long int suma=1;
for(long int i=1; i<=x;i++)
{
suma=suma*i;
}
std::cout<<suma<<std::endl;
}
int main(){
long int x = 13;
std::cout<<"Now calling the constexpr"<<std::endl;
auto start1 = get_time::now();
std::cout<<factorialC(x)<<std::endl;
auto end1 = get_time::now();
std::cout<<"Now calling the normal"<<std::endl;
auto start2 = get_time::now();
factorial(x);
auto end2 = get_time::now();
std::cout<<"Elapsed time for constexpr is "<<std::chrono::duration_cast<ns>(end1-start1).count()
<<" Elapsed time for normal is "<<std::chrono::duration_cast<ns>(end2-start2).count()<<std::endl;
}
When I run the code I am getting
Now calling the constexpr
1932053504
Now calling the normal
1932053504
Elapsed time for constexpr is 81812 Elapsed time for normal is 72428
But constexpr
should take nearly "0" time because it has already been calculated during compilation time .
But surprisingly constexpr
calculation takes more time than a normal factorial to work.
I have tried to follow this question, but I am not able understand the answer in my context.
Please help me to understand it.
I compiled the code through (filename is constexpr.cpp)
g++ --std=c++11 constexpr.cpp
V2:-
after @rici input, I did change line number 18 to
const long int x =13;
The results now are
Now calling the constexpr
1932053504
Now calling the normal
1932053504
Elapsed time for constexpr is 114653 Elapsed time for normal is 119052
It seems once I mentioned the x to be const, the compiler is calculating factorialC at compile time
I am using 4.9.3 version of g++ from MinGW32 on windows