static - 静态数组的展开循环

标签 static d loop-unrolling static-array iota

如果我调用该函数

/** Check if all Elements, possibly recursively, of $(D x) are zero. */
bool allZero(T)(in T x) @safe pure nothrow {
    import std.range: isIterable;
    static if (isIterable!T) {
        foreach (ref elt; x) {
            if (!elt.allZero) { return false; }
        }
        return true;
    } else {
        return x == 0;
    }
}

使用静态数组,D 会在 Release模式下自动为我展开 foreach 吗?

如果不可以

/** Static Iota. */
import std.typetuple: TypeTuple;
template siota(size_t from, size_t to) { alias siotaImpl!(to-1, from) siota; }
private template siotaImpl(size_t to, size_t now) {
    static if (now >= to) { alias TypeTuple!(now) siotaImpl; }
    else                  { alias TypeTuple!(now, siotaImpl!(to, now+1)) siotaImpl; }
}

用来代替foreach实现展开?

此外,DMD 是否有一个生成汇编代码的标志,以便我自己将来可以调查 DMD 生成的代码?

更新:这是我迄今为止的解决方案。

/** Check if all Elements, possibly recursively, of $(D x) are zero. */
bool allZero(T, bool useStatic = true)(in T x) @safe pure nothrow { // TODO: Extend to support struct's and classes's'
    static        if (useStatic && isStaticArray!T) {
        foreach (ix; siota!(0, x.length)) {
            if (!x[ix].allZero) { return false; } // make use of siota?
        }
        return true;
    } else static if (isIterable!T) {
        foreach (ref elt; x) {
            if (!elt.allZero) { return false; }
        }
        return true;
    } else {
        return x == 0;
    }
}

看起来还好吗?

最佳答案

with a static array will D unroll the foreach for me automatically?

不,该语言不能保证这一点。某些实现(编译器)可能会展开循环作为优化。

If not could my implementation of static iota (siota) be used to achieve this?

是的,在元组上使用 foreach 会为每次“迭代”生成代码,从而有效地展开循环。

Further is there a flag to DMD that generates assembly code so that I myself, in the future, can investigate the code generated by DMD?

不,DMD 无法发出程序集列表。您可以使用反汇编程序(例如 obj2asmIDA )或其他编译器。

关于static - 静态数组的展开循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21615791/

相关文章:

c++ - lua/C++ 对象与静态成员的绑定(bind)

string - 我应该如何处理 D 中的 C 字符串?

java - 如何测试静态方法是否线程安全

php - 每个人都使用相同的变量 php?

php - 从实例调用静态函数

arrays - 用 D 语言添加两个数组背后的机制

c++ - D 和 C++ 目前的互操作状态

javascript - 为什么 V8 和 spidermonkey 似乎都没有展开静态循环?

c - 为什么 clang 无法展开循环(gcc 展开)?

metaprogramming - 循环展开?在 Julia 中使用元编程