c++ - 通过缓存元函数优化编译时性能

标签 c++ templates instantiation template-meta-programming boost-mpl

假设我有以下元函数:

template <typename T>
struct make_pair {
    using type = std::pair<
        typename std::remove_reference<T>::type,
        typename std::remove_reference<T>::type
    >;
};

改为这样做(或其他)会提高编译速度吗?

template <typename T>
struct make_pair {
    using without_reference = typename std::remove_reference<T>::type;
    using type = std::pair<without_reference, without_reference>;
};

我看到了两种可能性:

  1. 编译器每次看到typename std::remove_reference<T>::type 都得做一些工作。 .使用中间别名具有某种“缓存”行为,它允许编译器只执行一次某些工作。

  2. 编译时性能是根据编译器必须执行的模板实例化的数量来衡量的。因为std::remove_reference<T>::type指与 std::remove_reference<T>::type 相同的类型,在这两种情况下只需要一个模板实例化,因此两种实现都具有相同的 WRT 编译时性能。

我认为 B 是对的,但我想确定一下。如果答案是编译器特定的,我最有兴趣知道 Clang 和 GCC 的答案。

编辑:

我对测试程序的编译进行了基准测试,以获取一些可以使用的数据。测试程序做了这样的事情:

template <typename ...> struct result;    

template <typename T>
struct with_cache {
    using without_reference = typename std::remove_reference<T>::type;
    using type = result<without_reference, ..., without_reference>;
};

template <typename T>
struct without_cache {
    using type = result<
        typename std::remove_reference<T>::type,
        ...,
        typename std::remove_reference<T>::type
    >;
{ };

using Result = with[out]_cache<int>::type;

这些是程序 10 次编译的平均时间,result<> 中有 10 000 个模板参数.

                -------------------------
                | g++ 4.8 | clang++ 3.2 |
-----------------------------------------
| with cache    | 0.1628s | 0.3036s     |
-----------------------------------------
| without cache | 0.1573s | 0.3785s     |
-----------------------------------------

测试程序由可用的脚本生成here .

最佳答案

我不能说所有编译器都是如此,但 GCC 以及很可能所有其他主要编译器都将使用 memoization。如果您考虑一下,它几乎必须这样做。

考虑下面的代码

&f<X, Y>::some_value == &f<X, Y>::some_value

这是必须的,因此编译器必须确保它不会重复定义方法和静态成员。现在可能有其他方法可以做到这一点,但这只是让我尖叫内存;我什至看不到另一种实现方式(当然,我已经非常努力地考虑过)

当我使用 TMP 时,我希望会发生内存。如果不这样做,那将是一个真正的痛苦,太慢了。我看到编译时性能主要差异的唯一方法是:a)使用更快的编译器,如 Clang(比 GCC 快 3 倍)并选择不同的算法。在我看来,小的常数因素在 TMP 中的影响甚至比在我的经验中对 C 或 C++ 的影响还要小。选择正确的算法,尽量不要做不必要的工作,尽量减少实例化的数量,并使用好的编译器(MSVC++ 真的很慢,而且远不符合 C++11,但 GCC 和 Clang 是相当好);这就是你真正能做的。

此外,您应该始终牺牲编译时间以获得更好的代码。过早的编译时优化比普通的过早优化更邪恶。如果由于某种原因性能变得严重阻碍开发,则可能会有异常(exception);但是我从来没有听说过这样的案例。

关于c++ - 通过缓存元函数优化编译时性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17203558/

相关文章:

javascript - 对象不会被创建?

c++ - 在 C++ 中获取广泛的类型错误

c++ - 使用嵌套的 boost::binds

c++ - 表达式模板需要冗余重载

c++ - 这个 RAII 独占资源检查对象/管理器组合线程安全吗?

json - Scala 2.10,它对 JSON 库和案例类验证/创建的影响

c++ - 为什么我应该/不应该使用 "new"运算符来实例化一个类,为什么?

C++ 方法的多重定义或 undefined reference

C++17:显式转换函数 vs 显式构造函数 + 隐式转换——规则改变了吗?

c++ - 添加到动态数组