且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

constexpr在运行时性能较差

更新时间:2023-02-19 23:24:26

问题在于,不能保证在编译时对 constexpr 进行评估.关键字 constexpr 只是说它可以,但是编译器也可以在运行时随意评估它.

The problem is that something constexpr is not guaranteed to be evaluated at compile time. The keyword constexpr just says that it can, but the compiler is free to evaluate it at run time too, as it sees fit.

运行时间的差异可能是因为您1)做得不够(一次迭代没什么),2)递归不如迭代快(我认为,尽管差异很小).

The difference in run time is probably because you 1) aren't doing it enough (one iteration is nothing) and 2) recursion isn't as fast as iteration (I think, although the difference is minimal).

为了保证编译时评估,您将不得不在编译器必须在编译时对其进行评估的上下文中使用它,例如模板:

To guarantee compile time evaluation, you will have to use it in a context where the compiler has to evaluate it at compile time, something like a template for example:

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();

还有一个用于 evaluate 的标准库函数, 查看全文