sri*_*h29 4 c++ performance constexpr c++11
我编写了以下代码来测试constexpr析因与正常方式评估所用的时间
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我得到了
Now calling the constexpr
1932053504
Now calling the normal
1932053504
Elapsed time for constexpr is 81812 Elapsed time for normal is 72428
Run Code Online (Sandbox Code Playgroud)
但是constexpr应该花费近乎"0"的时间,因为它已经在编译期间计算过了.
但令人惊讶的是,constexpr计算需要比正常因子工作更多的时间.我试图按照这个问题,但我无法理解我的背景.
请帮我理解一下.
我编译了代码(文件名是constexpr.cpp)
g++ --std=c++11 constexpr.cpp
Run Code Online (Sandbox Code Playgroud)
在@rici输入之后,我确实将第18行更改为
const long int x =13;
Run Code Online (Sandbox Code Playgroud)
结果现在是
Now calling the constexpr
1932053504
Now calling the normal
1932053504
Elapsed time for constexpr is 114653 Elapsed time for normal is 119052
Run Code Online (Sandbox Code Playgroud)
似乎有一次我提到x为const,编译器在编译时计算factorialC
我在Windows上使用MinGW32的4.9.3版g ++
问题是无法保证在编译时评估某些constexpr内容.该关键字只是说它可以,但编译器也可以在运行时自由地评估它,因为它认为合适.constexpr
运行时间的差异可能是因为你1)做得不够(一次迭代什么都没有)和2)递归没有迭代那么快(我认为,尽管差异很小).
为了保证编译时评估,您必须在编译器必须在编译时对其进行评估的上下文中使用它,例如模板:
template<unsigned long long n>
auto evaluate() { return n; }
//...
auto start1 = get_time::now();
std::cout << evaluate<factorialC(x)>() << std::endl; //factorialC is evaluted
//at compile timme
auto end1 = get_time::now();
Run Code Online (Sandbox Code Playgroud)
还有一个标准库函数evaluate,std::integral_constant.你可以改用它.
| 归档时间: |
|
| 查看次数: |
839 次 |
| 最近记录: |