繁体   English   中英

是否可以在编译时初始化数组,以便在运行时不需要时间?

[英]Is it possible to initialize an array at compile-time so it doesn't take time at run-time?

例如,如果我想创建多达 200 万个 Eratosthenes 筛,在运行时将需要一些时间。 有没有办法通过使用元编程来减少运行时间?

Sieve 的代码(将 std::bitset 初始化为const MILLION ):

void initCiur(std::bitset<MILLION> &c)
{
    c[0] = c[1] = 1;
    for (int i=4; i <= MILLION; i+=2)
        c[i] = 1;
    for (int i=3; i*i <= MILLION; i+=2)
        if (!c[i])
            for (int j=3*i; j <= MILLION; j+=2*i)
                c[j] = 1;
}

有没有办法通过使用元编程来减少运行时间?

当然是的。 我对“元编程”的理解非常广泛,就像任何程序生成代码一样(不仅仅是聪明的 C++ 模板)。

在大多数C++ 实现上(例如,如果在某些GNU/Linux操作系统上使用一些最近的GCC编译器),C++翻译单元实际上是一个文本文件 另请阅读 C++11 标准n3337

So just configure your build automation tool (eg GNU make or ninja ) to generate at build time (perhaps with a Python or Guile script, or your C++ metaprogram) some C++ file, or some file that would be #include -d elsewhere. 或者写你的GCC 插件这样做。

BTW, this idea is not new: ANTLR and GNU bison or Qt or SWIG do so (and recent GCC compilers -eg GCC 10 - have a dozen of specialized C++ code generators). 而我放弃的项目GCC MELT就是这样做的。 RefPerSysbismon 也是如此(对于哈希表中有用的素数,这两个都是我开始的项目)。 primes_rps.cc文件的部分内容是机器生成的(请参阅其中的注释)。

某些情况下,一个聪明的优化编译器可以优化constexpr的东西。 请注意赖斯定理,它指出并不总是可以巧妙地优化。 另见本报告草稿

您还可能对代码生成库感兴趣,例如asmjitlibgccjit ,或在运行时生成插件(在 Linux 上,您将使用dlopen(3)dlsym(3) ,但首先阅读C++ dlopen mini- how编写共享库)。

PS。 对于其他操作系统(例如 Windows)和 C++ 编译器,情况可能会有所不同,但上述大多数想法都是可重用的。 阅读 C++编译器操作系统的文档。 交叉编译方法中,您可能需要更多技巧。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM