constexpr 问题,为什么这两个不同的程序在 g++ 中运行的时间如此不同? [英] constexpr question, why do these two different programs run in such a different amount of time with g++?

查看:16
本文介绍了constexpr 问题,为什么这两个不同的程序在 g++ 中运行的时间如此不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 gcc 4.6.1,并且遇到了一些有趣的行为,涉及调用 constexpr 函数.该程序运行良好,并立即打印出 12200160415121876738.

I'm using gcc 4.6.1 and am getting some interesting behavior involving calling a constexpr function. This program runs just fine and straight away prints out 12200160415121876738.

#include <iostream>

extern const unsigned long joe;

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

const unsigned long joe = fib(92);

int main()
{
   ::std::cout << "Here I am!
";
   ::std::cout << joe << '
';
   return 0;
}

这个程序需要很长时间才能运行,我从来没有耐心等待它打印出一个值:

This program takes forever to run and I've never had the patience to wait for it to print out a value:

#include <iostream>

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

int main()
{
   ::std::cout << "Here I am!
";
   ::std::cout << fib(92) << '
';
   return 0;
}

为什么会有这么大的差异?我在第二个程序中做错了吗?

Why is there such a huge difference? Am I doing something wrong in the second program?

我在 64 位平台上使用 g++ -std=c++0x -O3 进行编译.

I'm compiling this with g++ -std=c++0x -O3 on a 64-bit platform.

推荐答案

joe 是一个整型常量表达式;它必须在数组范围内可用.因此,合理的编译器会在编译时对其进行评估.

joe is an Integral Constant Expression; it must be usable in array bounds. For that reason, a reasonable compiler will evaluate it at compile time.

在您的第二个程序中,即使编译器可以在编译时计算它,也没有理由必须这样做.

In your second program, even though the compiler could calculate it at compile time, there's no reason why it must.

这篇关于constexpr 问题,为什么这两个不同的程序在 g++ 中运行的时间如此不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆