You need to enable JavaScript to run this app. 为何constexpr变量初始化疑似在运行时求值,编译耗时远低于const版本?
优惠活动
大模型
产品
解决方案
定价
更多

为何constexpr变量初始化疑似在运行时求值,编译耗时远低于const版本?

对constexpr与const编译行为差异的困惑

我对constexpr的原有认知:该关键字用于告知编译器表达式可在编译期完成求值。具体而言:

  • 变量声明处的constexpr表示该变量的值可在编译期计算得到
  • 函数声明处的constexpr表示该函数可在编译期被调用并计算返回值,若函数在运行时被调用,则行为与普通函数一致

测试代码

#include <iostream>

using namespace std;

constexpr long int fib(int n)
{
    return (n <= 1)? n : fib(n-1) + fib(n-2);
}

int main ()
{
    constexpr long int res = fib(32);
    // const long int res = fib(32);
    
    cout << res << endl;
    return 0;
}

测试结果记录

场景1:使用constexpr修饰结果变量

我原本预期递归计算斐波那契数的写法会让编译过程耗费较长时间,但实际编译耗时远低于预期:

$ time g++ test.cpp
real    0m0.290s
user    0m0.252s
sys     0m0.035s

场景2:将结果变量替换为const修饰

我将代码中的constexpr long int res = fib(32);修改为const long int res = fib(32);后,编译耗时出现大幅上升:

$ time g++ test.cpp
real    0m5.830s
user    0m5.568s
sys     0m0.233s

核心疑问

测试结果和预期呈现出完全相反的表现:看起来const修饰的写法促使fib(32)在编译期完成求值,才导致编译耗时暴涨;而标注了constexpr的写法编译速度极快,反倒像是把求值过程留到了运行时,这和我之前对两个关键字的认知完全不符。

测试环境:Ubuntu 18.04,使用编译器版本为g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0


内容的提问来源于stack exchange,提问作者Yves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.06 06:36:07